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
shaoshuai0102/sief
lib/plugins/weibo.com.js
run
function run(data) { var cookies = cookie.parse(data.cookies); debug('cookies: ', cookies); request({ method: 'POST', url: 'http://weibo.com/aj/mblog/add?_wv=5&__rnd=' + (new Date).getTime(), headers: { Cookie: data.cookies, Referer: data.referer }, form: 'text=you%20are%20attacked' + (new Date).getTime() + '&pic_id=&rank=0&rankid=&_surl=&hottopicid=&location=home&module=stissue&_t=0' }, function(err, res, body) { debug('err', err); debug('body', body); }); }
javascript
function run(data) { var cookies = cookie.parse(data.cookies); debug('cookies: ', cookies); request({ method: 'POST', url: 'http://weibo.com/aj/mblog/add?_wv=5&__rnd=' + (new Date).getTime(), headers: { Cookie: data.cookies, Referer: data.referer }, form: 'text=you%20are%20attacked' + (new Date).getTime() + '&pic_id=&rank=0&rankid=&_surl=&hottopicid=&location=home&module=stissue&_t=0' }, function(err, res, body) { debug('err', err); debug('body', body); }); }
[ "function", "run", "(", "data", ")", "{", "var", "cookies", "=", "cookie", ".", "parse", "(", "data", ".", "cookies", ")", ";", "debug", "(", "'cookies: '", ",", "cookies", ")", ";", "request", "(", "{", "method", ":", "'POST'", ",", "url", ":", "'http://weibo.com/aj/mblog/add?_wv=5&__rnd='", "+", "(", "new", "Date", ")", ".", "getTime", "(", ")", ",", "headers", ":", "{", "Cookie", ":", "data", ".", "cookies", ",", "Referer", ":", "data", ".", "referer", "}", ",", "form", ":", "'text=you%20are%20attacked'", "+", "(", "new", "Date", ")", ".", "getTime", "(", ")", "+", "'&pic_id=&rank=0&rankid=&_surl=&hottopicid=&location=home&module=stissue&_t=0'", "}", ",", "function", "(", "err", ",", "res", ",", "body", ")", "{", "debug", "(", "'err'", ",", "err", ")", ";", "debug", "(", "'body'", ",", "body", ")", ";", "}", ")", ";", "}" ]
request.debug = true;
[ "request", ".", "debug", "=", "true", ";" ]
eeaf5e4363505021ec28783827d35c17dca3074c
https://github.com/shaoshuai0102/sief/blob/eeaf5e4363505021ec28783827d35c17dca3074c/lib/plugins/weibo.com.js#L7-L22
train
pmlopes/webpack-vertx-plugin
index.js
getMaven
function getMaven(dir) { var mvn = 'mvn'; var isWin = /^win/.test(process.platform); // check for wrapper if (isWin) { if (fs.existsSync(path.resolve(dir, 'mvnw.bat'))) { mvn = path.resolve(dir, 'mvnw.bat'); } } else { if (fs.existsSync(path.resolve(dir, 'mvnw'))) { mvn = path.resolve(dir, 'mvnw'); } } return mvn; }
javascript
function getMaven(dir) { var mvn = 'mvn'; var isWin = /^win/.test(process.platform); // check for wrapper if (isWin) { if (fs.existsSync(path.resolve(dir, 'mvnw.bat'))) { mvn = path.resolve(dir, 'mvnw.bat'); } } else { if (fs.existsSync(path.resolve(dir, 'mvnw'))) { mvn = path.resolve(dir, 'mvnw'); } } return mvn; }
[ "function", "getMaven", "(", "dir", ")", "{", "var", "mvn", "=", "'mvn'", ";", "var", "isWin", "=", "/", "^win", "/", ".", "test", "(", "process", ".", "platform", ")", ";", "if", "(", "isWin", ")", "{", "if", "(", "fs", ".", "existsSync", "(", "path", ".", "resolve", "(", "dir", ",", "'mvnw.bat'", ")", ")", ")", "{", "mvn", "=", "path", ".", "resolve", "(", "dir", ",", "'mvnw.bat'", ")", ";", "}", "}", "else", "{", "if", "(", "fs", ".", "existsSync", "(", "path", ".", "resolve", "(", "dir", ",", "'mvnw'", ")", ")", ")", "{", "mvn", "=", "path", ".", "resolve", "(", "dir", ",", "'mvnw'", ")", ";", "}", "}", "return", "mvn", ";", "}" ]
Helper to select local maven wrapper or system maven @param dir current working directory @returns {string} the maven command
[ "Helper", "to", "select", "local", "maven", "wrapper", "or", "system", "maven" ]
de15ee291c21c5303f36b53b7ae4a93eec850b17
https://github.com/pmlopes/webpack-vertx-plugin/blob/de15ee291c21c5303f36b53b7ae4a93eec850b17/index.js#L21-L37
train
AlexanderOMara/bootstrap-node
src/index.js
getBootstrapNode
function getBootstrapNode() { // Use the cache if already found. if (cache) { return cache; } // Get the debug object. var Debug = require('vm').runInDebugContext('Debug'); // Use the debug object to list all of the scripts. // It is only possible to get the scripts is a listener is set. // However, we do not want to replace any existing listeners. // First try to get the scripts without setting a litener. // If it fails, then there must be not be any listener set. // Set listener temporarily, get the scripts, and unset. var scripts; try { scripts = Debug.scripts(); } catch (ex) { Debug.setListener(function() {}); scripts = Debug.scripts(); Debug.setListener(null); } // Now find the script in whole the list. for (var i = scripts.length; i--;) { var script = scripts[i]; var name = script.name; // Check the script name, ignore if not a known name. if ( name !== 'bootstrap_node.js' && name !== 'node.js' ) { continue; } // Get the script source. var source = script.source; // Get the body of the code. var body = source .replace(trimHeader, '') .replace(trimFooter, ''); // Check if the body matches and cache it. if (matchBody.test(body)) { cache = source; break; } } // Throw if not found. if (!cache) { throw new Error('Node bootstrap script was not found.'); } return cache; }
javascript
function getBootstrapNode() { // Use the cache if already found. if (cache) { return cache; } // Get the debug object. var Debug = require('vm').runInDebugContext('Debug'); // Use the debug object to list all of the scripts. // It is only possible to get the scripts is a listener is set. // However, we do not want to replace any existing listeners. // First try to get the scripts without setting a litener. // If it fails, then there must be not be any listener set. // Set listener temporarily, get the scripts, and unset. var scripts; try { scripts = Debug.scripts(); } catch (ex) { Debug.setListener(function() {}); scripts = Debug.scripts(); Debug.setListener(null); } // Now find the script in whole the list. for (var i = scripts.length; i--;) { var script = scripts[i]; var name = script.name; // Check the script name, ignore if not a known name. if ( name !== 'bootstrap_node.js' && name !== 'node.js' ) { continue; } // Get the script source. var source = script.source; // Get the body of the code. var body = source .replace(trimHeader, '') .replace(trimFooter, ''); // Check if the body matches and cache it. if (matchBody.test(body)) { cache = source; break; } } // Throw if not found. if (!cache) { throw new Error('Node bootstrap script was not found.'); } return cache; }
[ "function", "getBootstrapNode", "(", ")", "{", "if", "(", "cache", ")", "{", "return", "cache", ";", "}", "var", "Debug", "=", "require", "(", "'vm'", ")", ".", "runInDebugContext", "(", "'Debug'", ")", ";", "var", "scripts", ";", "try", "{", "scripts", "=", "Debug", ".", "scripts", "(", ")", ";", "}", "catch", "(", "ex", ")", "{", "Debug", ".", "setListener", "(", "function", "(", ")", "{", "}", ")", ";", "scripts", "=", "Debug", ".", "scripts", "(", ")", ";", "Debug", ".", "setListener", "(", "null", ")", ";", "}", "for", "(", "var", "i", "=", "scripts", ".", "length", ";", "i", "--", ";", ")", "{", "var", "script", "=", "scripts", "[", "i", "]", ";", "var", "name", "=", "script", ".", "name", ";", "if", "(", "name", "!==", "'bootstrap_node.js'", "&&", "name", "!==", "'node.js'", ")", "{", "continue", ";", "}", "var", "source", "=", "script", ".", "source", ";", "var", "body", "=", "source", ".", "replace", "(", "trimHeader", ",", "''", ")", ".", "replace", "(", "trimFooter", ",", "''", ")", ";", "if", "(", "matchBody", ".", "test", "(", "body", ")", ")", "{", "cache", "=", "source", ";", "break", ";", "}", "}", "if", "(", "!", "cache", ")", "{", "throw", "new", "Error", "(", "'Node bootstrap script was not found.'", ")", ";", "}", "return", "cache", ";", "}" ]
Get the Node bootstrap script source. @throws Error - If script not found. @returns {string} - Script source.
[ "Get", "the", "Node", "bootstrap", "script", "source", "." ]
c3b08faf71c553feff9c31ab1772e71be5fd9fbd
https://github.com/AlexanderOMara/bootstrap-node/blob/c3b08faf71c553feff9c31ab1772e71be5fd9fbd/src/index.js#L28-L87
train
mikolalysenko/3p
lib/decoder.js
buildStars
function buildStars(numVerts, cells) { var stars = new Array(numVerts) for(var i=0; i<numVerts; ++i) { stars[i] = [] } var numCells = cells.length for(var i=0; i<numCells; ++i) { var f = cells[i] for(var j=0; j<3; ++j) { stars[f[j]].push(i) } } return stars }
javascript
function buildStars(numVerts, cells) { var stars = new Array(numVerts) for(var i=0; i<numVerts; ++i) { stars[i] = [] } var numCells = cells.length for(var i=0; i<numCells; ++i) { var f = cells[i] for(var j=0; j<3; ++j) { stars[f[j]].push(i) } } return stars }
[ "function", "buildStars", "(", "numVerts", ",", "cells", ")", "{", "var", "stars", "=", "new", "Array", "(", "numVerts", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numVerts", ";", "++", "i", ")", "{", "stars", "[", "i", "]", "=", "[", "]", "}", "var", "numCells", "=", "cells", ".", "length", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numCells", ";", "++", "i", ")", "{", "var", "f", "=", "cells", "[", "i", "]", "for", "(", "var", "j", "=", "0", ";", "j", "<", "3", ";", "++", "j", ")", "{", "stars", "[", "f", "[", "j", "]", "]", ".", "push", "(", "i", ")", "}", "}", "return", "stars", "}" ]
Construct all stars of a mesh
[ "Construct", "all", "stars", "of", "a", "mesh" ]
e8148a633303d65db1a81e1ef3761c811536c113
https://github.com/mikolalysenko/3p/blob/e8148a633303d65db1a81e1ef3761c811536c113/lib/decoder.js#L8-L21
train
zaim/immpatch
lib/parse.js
clone
function clone(obj) { var key; var copy = {}; for (key in obj) { /* istanbul ignore else */ if (hop.call(obj, key)) { copy[key] = obj[key]; } } return copy; }
javascript
function clone(obj) { var key; var copy = {}; for (key in obj) { /* istanbul ignore else */ if (hop.call(obj, key)) { copy[key] = obj[key]; } } return copy; }
[ "function", "clone", "(", "obj", ")", "{", "var", "key", ";", "var", "copy", "=", "{", "}", ";", "for", "(", "key", "in", "obj", ")", "{", "if", "(", "hop", ".", "call", "(", "obj", ",", "key", ")", ")", "{", "copy", "[", "key", "]", "=", "obj", "[", "key", "]", ";", "}", "}", "return", "copy", ";", "}" ]
Shallow-clone an object.
[ "Shallow", "-", "clone", "an", "object", "." ]
039647d10506bc928f95c962f7cd5950574637e8
https://github.com/zaim/immpatch/blob/039647d10506bc928f95c962f7cd5950574637e8/lib/parse.js#L91-L101
train
zaim/immpatch
lib/parse.js
parse
function parse(op, target) { if (OPERATORS.indexOf(op.op) !== -1) { op = clone(op); if (op.from != null) { op.from = parsePointer(op.from); } if (op.path != null) { op.path = parsePointer(op.path); } else { throw new error.InvalidOperationError(op.op, 'Operation object must have a "path" member'); } validatePath(op.from || op.path, target); return op; } throw new error.InvalidOperationError('Operation object "op" member must be one of ' + OPERATORS.join(', ') + ' ' + ('but got "' + op.op + '"')); }
javascript
function parse(op, target) { if (OPERATORS.indexOf(op.op) !== -1) { op = clone(op); if (op.from != null) { op.from = parsePointer(op.from); } if (op.path != null) { op.path = parsePointer(op.path); } else { throw new error.InvalidOperationError(op.op, 'Operation object must have a "path" member'); } validatePath(op.from || op.path, target); return op; } throw new error.InvalidOperationError('Operation object "op" member must be one of ' + OPERATORS.join(', ') + ' ' + ('but got "' + op.op + '"')); }
[ "function", "parse", "(", "op", ",", "target", ")", "{", "if", "(", "OPERATORS", ".", "indexOf", "(", "op", ".", "op", ")", "!==", "-", "1", ")", "{", "op", "=", "clone", "(", "op", ")", ";", "if", "(", "op", ".", "from", "!=", "null", ")", "{", "op", ".", "from", "=", "parsePointer", "(", "op", ".", "from", ")", ";", "}", "if", "(", "op", ".", "path", "!=", "null", ")", "{", "op", ".", "path", "=", "parsePointer", "(", "op", ".", "path", ")", ";", "}", "else", "{", "throw", "new", "error", ".", "InvalidOperationError", "(", "op", ".", "op", ",", "'Operation object must have a \"path\" member'", ")", ";", "}", "validatePath", "(", "op", ".", "from", "||", "op", ".", "path", ",", "target", ")", ";", "return", "op", ";", "}", "throw", "new", "error", ".", "InvalidOperationError", "(", "'Operation object \"op\" member must be one of '", "+", "OPERATORS", ".", "join", "(", "', '", ")", "+", "' '", "+", "(", "'but got \"'", "+", "op", ".", "op", "+", "'\"'", ")", ")", ";", "}" ]
Parse and validate the patch operation. Converts `op.path` (and `op.from` if available) to an array. @param {object} op @param {Immutable} target @returns {object} op
[ "Parse", "and", "validate", "the", "patch", "operation", "." ]
039647d10506bc928f95c962f7cd5950574637e8
https://github.com/zaim/immpatch/blob/039647d10506bc928f95c962f7cd5950574637e8/lib/parse.js#L114-L129
train
LaunchPadLab/lp-redux-api
src/handlers/set-on-success.js
setOnSuccess
function setOnSuccess (path, transform=getDataFromAction) { return handleSuccess((state, action) => set(path, transform(action, state), state)) }
javascript
function setOnSuccess (path, transform=getDataFromAction) { return handleSuccess((state, action) => set(path, transform(action, state), state)) }
[ "function", "setOnSuccess", "(", "path", ",", "transform", "=", "getDataFromAction", ")", "{", "return", "handleSuccess", "(", "(", "state", ",", "action", ")", "=>", "set", "(", "path", ",", "transform", "(", "action", ",", "state", ")", ",", "state", ")", ")", "}" ]
A function that creates an API action handler that sets a path in the state with the returned data if a request succeeds. @name setOnSuccess @param {String} path - The path in the state to set with the returned data @param {Function} [transform] - A function that determines the data that is set in the state. Passed `action` and `state` params. @returns {Function} An action handler that runs when a request is unsuccessful @example handleActions({ // This will do the same thing as the example for handleSuccess [apiActions.fetchUser]: setOnSuccess('currentSuccess') })
[ "A", "function", "that", "creates", "an", "API", "action", "handler", "that", "sets", "a", "path", "in", "the", "state", "with", "the", "returned", "data", "if", "a", "request", "succeeds", "." ]
73eee231067365326780ddc1dbbfa50d3e65defc
https://github.com/LaunchPadLab/lp-redux-api/blob/73eee231067365326780ddc1dbbfa50d3e65defc/src/handlers/set-on-success.js#L21-L23
train
LaunchPadLab/lp-redux-api
src/handlers/set-on-failure.js
setOnFailure
function setOnFailure (path, transform=getDataFromAction) { return handleFailure((state, action) => set(path, transform(action, state), state)) }
javascript
function setOnFailure (path, transform=getDataFromAction) { return handleFailure((state, action) => set(path, transform(action, state), state)) }
[ "function", "setOnFailure", "(", "path", ",", "transform", "=", "getDataFromAction", ")", "{", "return", "handleFailure", "(", "(", "state", ",", "action", ")", "=>", "set", "(", "path", ",", "transform", "(", "action", ",", "state", ")", ",", "state", ")", ")", "}" ]
A function that creates an API action handler that sets a path in the state with the returned error if a request fails. @name setOnFailure @param {String} path - The path in the state to set with the returned error @param {Function} [transform] - A function that determines the data that is set in the state. Passed `action` and `state` params. @returns {Function} An action handler that runs when a request is successful @example handleActions({ // This will do the same thing as the example for handleFailure [apiActions.fetchUser]: setOnFailure('userFetchError') })
[ "A", "function", "that", "creates", "an", "API", "action", "handler", "that", "sets", "a", "path", "in", "the", "state", "with", "the", "returned", "error", "if", "a", "request", "fails", "." ]
73eee231067365326780ddc1dbbfa50d3e65defc
https://github.com/LaunchPadLab/lp-redux-api/blob/73eee231067365326780ddc1dbbfa50d3e65defc/src/handlers/set-on-failure.js#L21-L23
train
axke/rs-api
lib/apis/distraction/circus.js
Circus
function Circus() { const LOCATIONS = [ 'Tree Gnome Stronghold', 'Seers\' Village', 'Catherby', 'Taverley', 'Edgeville', 'Falador', 'Rimmington', 'Draynor Village', 'Al Kharid', 'Lumbridge', 'Lumber Yard', 'Gertrude\'s House' ]; this.getRotation = function() { return new Promise(function (resolve, reject) { let locations = []; for (var i = 0; i < LOCATIONS.length; i++) { var now = new Date(); var daysToAdd = 7 * i; now.setDate(now.getDate() + daysToAdd); var currentLocation = Math.floor((((Math.floor((now / 1000) / (24 * 60 * 60))) + 1) % (7 * LOCATIONS.length)) / 7); var daysUntilNext = (7 - ((Math.floor((now / 1000) / (24 * 60 * 60))) + 1) % (7 * LOCATIONS.length) % 7) + daysToAdd; var start = new Date(); start.setDate(start.getDate() + (daysUntilNext - 7)); var obj = { location: LOCATIONS[currentLocation], daysUntilNext: daysUntilNext, startDate: start }; locations.push(obj); } resolve(locations); }); } }
javascript
function Circus() { const LOCATIONS = [ 'Tree Gnome Stronghold', 'Seers\' Village', 'Catherby', 'Taverley', 'Edgeville', 'Falador', 'Rimmington', 'Draynor Village', 'Al Kharid', 'Lumbridge', 'Lumber Yard', 'Gertrude\'s House' ]; this.getRotation = function() { return new Promise(function (resolve, reject) { let locations = []; for (var i = 0; i < LOCATIONS.length; i++) { var now = new Date(); var daysToAdd = 7 * i; now.setDate(now.getDate() + daysToAdd); var currentLocation = Math.floor((((Math.floor((now / 1000) / (24 * 60 * 60))) + 1) % (7 * LOCATIONS.length)) / 7); var daysUntilNext = (7 - ((Math.floor((now / 1000) / (24 * 60 * 60))) + 1) % (7 * LOCATIONS.length) % 7) + daysToAdd; var start = new Date(); start.setDate(start.getDate() + (daysUntilNext - 7)); var obj = { location: LOCATIONS[currentLocation], daysUntilNext: daysUntilNext, startDate: start }; locations.push(obj); } resolve(locations); }); } }
[ "function", "Circus", "(", ")", "{", "const", "LOCATIONS", "=", "[", "'Tree Gnome Stronghold'", ",", "'Seers\\' Village'", ",", "\\'", ",", "'Catherby'", ",", "'Taverley'", ",", "'Edgeville'", ",", "'Falador'", ",", "'Rimmington'", ",", "'Draynor Village'", ",", "'Al Kharid'", ",", "'Lumbridge'", ",", "'Lumber Yard'", "]", ";", "'Gertrude\\'s House'", "}" ]
Module containing Circus functions @module Circus
[ "Module", "containing", "Circus", "functions" ]
71af4973e1d079f09b7d888b6d24735784185942
https://github.com/axke/rs-api/blob/71af4973e1d079f09b7d888b6d24735784185942/lib/apis/distraction/circus.js#L10-L51
train
schlosser/substituteteacher.js
src/substituteteacher.js
_parseSentence
function _parseSentence(rawSentence) { if (!rawSentence || typeof rawSentence !== "string") { throw "rawSentence must be a string."; } var components = []; var start, end, endChar; for (start = 0, end = 0; end < rawSentence.length; end++) { endChar = rawSentence.charAt(end); /** * Characters that should "detach" from strings are: * ().,/![]*;:{}=?"+ or whitespace * Characters that remain that remain a part of the word include: * -#$%^&_`~' */ if (endChar.match(/[\.,"\/!\?\*\+;:{}=()\[\]\s]/g)) { // Append the word we've been building if (end > start) { if (endChar.match(/\s/g)) { components.push(rawSentence.slice(start, end) + "&nbsp;"); } else { components.push(rawSentence.slice(start, end)); } } // If the character is not whitespace, then it is a special character // and should be split off into its own string if (!endChar.match(/\s/g)) { if (end +1 < rawSentence.length && rawSentence.charAt(end + 1).match(/\s/g)) { components.push(endChar + "&nbsp;"); } else { components.push(endChar); } } // The start of the next word is the next character to be seen. start = end + 1; } } if (start < end) { components.push(rawSentence.slice(start, end)); } return components; }
javascript
function _parseSentence(rawSentence) { if (!rawSentence || typeof rawSentence !== "string") { throw "rawSentence must be a string."; } var components = []; var start, end, endChar; for (start = 0, end = 0; end < rawSentence.length; end++) { endChar = rawSentence.charAt(end); /** * Characters that should "detach" from strings are: * ().,/![]*;:{}=?"+ or whitespace * Characters that remain that remain a part of the word include: * -#$%^&_`~' */ if (endChar.match(/[\.,"\/!\?\*\+;:{}=()\[\]\s]/g)) { // Append the word we've been building if (end > start) { if (endChar.match(/\s/g)) { components.push(rawSentence.slice(start, end) + "&nbsp;"); } else { components.push(rawSentence.slice(start, end)); } } // If the character is not whitespace, then it is a special character // and should be split off into its own string if (!endChar.match(/\s/g)) { if (end +1 < rawSentence.length && rawSentence.charAt(end + 1).match(/\s/g)) { components.push(endChar + "&nbsp;"); } else { components.push(endChar); } } // The start of the next word is the next character to be seen. start = end + 1; } } if (start < end) { components.push(rawSentence.slice(start, end)); } return components; }
[ "function", "_parseSentence", "(", "rawSentence", ")", "{", "if", "(", "!", "rawSentence", "||", "typeof", "rawSentence", "!==", "\"string\"", ")", "{", "throw", "\"rawSentence must be a string.\"", ";", "}", "var", "components", "=", "[", "]", ";", "var", "start", ",", "end", ",", "endChar", ";", "for", "(", "start", "=", "0", ",", "end", "=", "0", ";", "end", "<", "rawSentence", ".", "length", ";", "end", "++", ")", "{", "endChar", "=", "rawSentence", ".", "charAt", "(", "end", ")", ";", "if", "(", "endChar", ".", "match", "(", "/", "[\\.,\"\\/!\\?\\*\\+;:{}=()\\[\\]\\s]", "/", "g", ")", ")", "{", "if", "(", "end", ">", "start", ")", "{", "if", "(", "endChar", ".", "match", "(", "/", "\\s", "/", "g", ")", ")", "{", "components", ".", "push", "(", "rawSentence", ".", "slice", "(", "start", ",", "end", ")", "+", "\"&nbsp;\"", ")", ";", "}", "else", "{", "components", ".", "push", "(", "rawSentence", ".", "slice", "(", "start", ",", "end", ")", ")", ";", "}", "}", "if", "(", "!", "endChar", ".", "match", "(", "/", "\\s", "/", "g", ")", ")", "{", "if", "(", "end", "+", "1", "<", "rawSentence", ".", "length", "&&", "rawSentence", ".", "charAt", "(", "end", "+", "1", ")", ".", "match", "(", "/", "\\s", "/", "g", ")", ")", "{", "components", ".", "push", "(", "endChar", "+", "\"&nbsp;\"", ")", ";", "}", "else", "{", "components", ".", "push", "(", "endChar", ")", ";", "}", "}", "start", "=", "end", "+", "1", ";", "}", "}", "if", "(", "start", "<", "end", ")", "{", "components", ".", "push", "(", "rawSentence", ".", "slice", "(", "start", ",", "end", ")", ")", ";", "}", "return", "components", ";", "}" ]
Parse the raw sentence into an array of words. Separate the sentence by spaces, and then go along each word and pull punctuation off words that end with a punctuation symbol: "We're here (in Wilkes-Barre), finally!" => ["We're", "here", "(", "in", "Wilkes-Barre", ")", ",", "finally", "!"] TODO: figure out some way to annotate puncatation so that it can be rendered without a space in it. @param {string[]} rawSentences the sentences to parse @returns {string[][]} sentences the sentences split up into tokens
[ "Parse", "the", "raw", "sentence", "into", "an", "array", "of", "words", "." ]
2c278ed803333d889f94dd75083e35d7d46b4d91
https://github.com/schlosser/substituteteacher.js/blob/2c278ed803333d889f94dd75083e35d7d46b4d91/src/substituteteacher.js#L38-L81
train
schlosser/substituteteacher.js
src/substituteteacher.js
_whichTransitionEndEvent
function _whichTransitionEndEvent() { var t; var el = document.createElement("fakeelement"); var transitions = { "WebkitTransition": "webkitTransitionEnd", "MozTransition": "transitionend", "MSTransition": "msTransitionEnd", "OTransition": "otransitionend", "transition": "transitionend", }; for (t in transitions) { if (transitions.hasOwnProperty(t)) { if (el.style[t] !== undefined) { return transitions[t]; } } } }
javascript
function _whichTransitionEndEvent() { var t; var el = document.createElement("fakeelement"); var transitions = { "WebkitTransition": "webkitTransitionEnd", "MozTransition": "transitionend", "MSTransition": "msTransitionEnd", "OTransition": "otransitionend", "transition": "transitionend", }; for (t in transitions) { if (transitions.hasOwnProperty(t)) { if (el.style[t] !== undefined) { return transitions[t]; } } } }
[ "function", "_whichTransitionEndEvent", "(", ")", "{", "var", "t", ";", "var", "el", "=", "document", ".", "createElement", "(", "\"fakeelement\"", ")", ";", "var", "transitions", "=", "{", "\"WebkitTransition\"", ":", "\"webkitTransitionEnd\"", ",", "\"MozTransition\"", ":", "\"transitionend\"", ",", "\"MSTransition\"", ":", "\"msTransitionEnd\"", ",", "\"OTransition\"", ":", "\"otransitionend\"", ",", "\"transition\"", ":", "\"transitionend\"", ",", "}", ";", "for", "(", "t", "in", "transitions", ")", "{", "if", "(", "transitions", ".", "hasOwnProperty", "(", "t", ")", ")", "{", "if", "(", "el", ".", "style", "[", "t", "]", "!==", "undefined", ")", "{", "return", "transitions", "[", "t", "]", ";", "}", "}", "}", "}" ]
Find the CSS transition end event that we should listen for. @returns {string} t - the transition string
[ "Find", "the", "CSS", "transition", "end", "event", "that", "we", "should", "listen", "for", "." ]
2c278ed803333d889f94dd75083e35d7d46b4d91
https://github.com/schlosser/substituteteacher.js/blob/2c278ed803333d889f94dd75083e35d7d46b4d91/src/substituteteacher.js#L88-L105
train
mikolalysenko/polytope-closest-point
lib/closest_point_1d.js
closestPoint1d
function closestPoint1d(a, b, x, result) { var denom = 0.0; var numer = 0.0; for(var i=0; i<x.length; ++i) { var ai = a[i]; var bi = b[i]; var xi = x[i]; var dd = ai - bi; numer += dd * (xi - bi); denom += dd * dd; } var t = 0.0; if(Math.abs(denom) > EPSILON) { t = numer / denom; if(t < 0.0) { t = 0.0; } else if(t > 1.0) { t = 1.0; } } var ti = 1.0 - t; var d = 0; for(var i=0; i<x.length; ++i) { var r = t * a[i] + ti * b[i]; result[i] = r; var s = x[i] - r; d += s * s; } return d; }
javascript
function closestPoint1d(a, b, x, result) { var denom = 0.0; var numer = 0.0; for(var i=0; i<x.length; ++i) { var ai = a[i]; var bi = b[i]; var xi = x[i]; var dd = ai - bi; numer += dd * (xi - bi); denom += dd * dd; } var t = 0.0; if(Math.abs(denom) > EPSILON) { t = numer / denom; if(t < 0.0) { t = 0.0; } else if(t > 1.0) { t = 1.0; } } var ti = 1.0 - t; var d = 0; for(var i=0; i<x.length; ++i) { var r = t * a[i] + ti * b[i]; result[i] = r; var s = x[i] - r; d += s * s; } return d; }
[ "function", "closestPoint1d", "(", "a", ",", "b", ",", "x", ",", "result", ")", "{", "var", "denom", "=", "0.0", ";", "var", "numer", "=", "0.0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "x", ".", "length", ";", "++", "i", ")", "{", "var", "ai", "=", "a", "[", "i", "]", ";", "var", "bi", "=", "b", "[", "i", "]", ";", "var", "xi", "=", "x", "[", "i", "]", ";", "var", "dd", "=", "ai", "-", "bi", ";", "numer", "+=", "dd", "*", "(", "xi", "-", "bi", ")", ";", "denom", "+=", "dd", "*", "dd", ";", "}", "var", "t", "=", "0.0", ";", "if", "(", "Math", ".", "abs", "(", "denom", ")", ">", "EPSILON", ")", "{", "t", "=", "numer", "/", "denom", ";", "if", "(", "t", "<", "0.0", ")", "{", "t", "=", "0.0", ";", "}", "else", "if", "(", "t", ">", "1.0", ")", "{", "t", "=", "1.0", ";", "}", "}", "var", "ti", "=", "1.0", "-", "t", ";", "var", "d", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "x", ".", "length", ";", "++", "i", ")", "{", "var", "r", "=", "t", "*", "a", "[", "i", "]", "+", "ti", "*", "b", "[", "i", "]", ";", "result", "[", "i", "]", "=", "r", ";", "var", "s", "=", "x", "[", "i", "]", "-", "r", ";", "d", "+=", "s", "*", "s", ";", "}", "return", "d", ";", "}" ]
Computes closest point to a line segment
[ "Computes", "closest", "point", "to", "a", "line", "segment" ]
de523419bf633743f4333d0768b5e929bc82fd80
https://github.com/mikolalysenko/polytope-closest-point/blob/de523419bf633743f4333d0768b5e929bc82fd80/lib/closest_point_1d.js#L6-L35
train
jaredLunde/react-broker
src/macro/index.js
evaluateMacros
function evaluateMacros({references, state, babel}) { references.default.forEach(referencePath => makeLegacyEnsure({ references, state, babel, referencePath })) }
javascript
function evaluateMacros({references, state, babel}) { references.default.forEach(referencePath => makeLegacyEnsure({ references, state, babel, referencePath })) }
[ "function", "evaluateMacros", "(", "{", "references", ",", "state", ",", "babel", "}", ")", "{", "references", ".", "default", ".", "forEach", "(", "referencePath", "=>", "makeLegacyEnsure", "(", "{", "references", ",", "state", ",", "babel", ",", "referencePath", "}", ")", ")", "}" ]
cycles through each call to the macro and determines an output for each
[ "cycles", "through", "each", "call", "to", "the", "macro", "and", "determines", "an", "output", "for", "each" ]
bc77d6ddb768c0d2fd57bc806ae60468067978f9
https://github.com/jaredLunde/react-broker/blob/bc77d6ddb768c0d2fd57bc806ae60468067978f9/src/macro/index.js#L9-L16
train
jaredLunde/react-broker
src/macro/index.js
makeLegacyEnsure
function makeLegacyEnsure ({references, state, babel, referencePath}) { const brokerTemplate = babel.template.smart(` (typeof Broker !== 'undefined' ? Broker : require('${pkgName}').default)( PROMISES, OPTIONS ) `, {preserveComments: true}) const {promises, options} = parseArguments( referencePath.parentPath.get('arguments'), state, babel ) // component options are always in the second argument // let options = referencePath.parentPath.get('arguments')[1] // options = options && options.expression // replaces the macro with the new broker template in the source code referencePath.parentPath.replaceWith( brokerTemplate({ PROMISES: toObjectExpression(promises, babel), OPTIONS: options }) ) referencePath.parentPath.get('arguments')[0].get('properties').forEach( prop => { // this adds webpack magic comment for chunks names // prop.get('key') is the key of the current property // prop.get('value') is the value of the current property // .get('value').get('body') is the import() call expression // .get('arguments')[0] is the first argument of the import(), which is the source prop.get('value').get('body').get('arguments')[0].addComment( "leading", ` webpackChunkName: ${prop.get('key')} ` ) } ) }
javascript
function makeLegacyEnsure ({references, state, babel, referencePath}) { const brokerTemplate = babel.template.smart(` (typeof Broker !== 'undefined' ? Broker : require('${pkgName}').default)( PROMISES, OPTIONS ) `, {preserveComments: true}) const {promises, options} = parseArguments( referencePath.parentPath.get('arguments'), state, babel ) // component options are always in the second argument // let options = referencePath.parentPath.get('arguments')[1] // options = options && options.expression // replaces the macro with the new broker template in the source code referencePath.parentPath.replaceWith( brokerTemplate({ PROMISES: toObjectExpression(promises, babel), OPTIONS: options }) ) referencePath.parentPath.get('arguments')[0].get('properties').forEach( prop => { // this adds webpack magic comment for chunks names // prop.get('key') is the key of the current property // prop.get('value') is the value of the current property // .get('value').get('body') is the import() call expression // .get('arguments')[0] is the first argument of the import(), which is the source prop.get('value').get('body').get('arguments')[0].addComment( "leading", ` webpackChunkName: ${prop.get('key')} ` ) } ) }
[ "function", "makeLegacyEnsure", "(", "{", "references", ",", "state", ",", "babel", ",", "referencePath", "}", ")", "{", "const", "brokerTemplate", "=", "babel", ".", "template", ".", "smart", "(", "`", "${", "pkgName", "}", "`", ",", "{", "preserveComments", ":", "true", "}", ")", "const", "{", "promises", ",", "options", "}", "=", "parseArguments", "(", "referencePath", ".", "parentPath", ".", "get", "(", "'arguments'", ")", ",", "state", ",", "babel", ")", "referencePath", ".", "parentPath", ".", "replaceWith", "(", "brokerTemplate", "(", "{", "PROMISES", ":", "toObjectExpression", "(", "promises", ",", "babel", ")", ",", "OPTIONS", ":", "options", "}", ")", ")", "referencePath", ".", "parentPath", ".", "get", "(", "'arguments'", ")", "[", "0", "]", ".", "get", "(", "'properties'", ")", ".", "forEach", "(", "prop", "=>", "{", "prop", ".", "get", "(", "'value'", ")", ".", "get", "(", "'body'", ")", ".", "get", "(", "'arguments'", ")", "[", "0", "]", ".", "addComment", "(", "\"leading\"", ",", "`", "${", "prop", ".", "get", "(", "'key'", ")", "}", "`", ")", "}", ")", "}" ]
if Broker is defined in the scope then it will use that Broker, otherwise it requires the module.
[ "if", "Broker", "is", "defined", "in", "the", "scope", "then", "it", "will", "use", "that", "Broker", "otherwise", "it", "requires", "the", "module", "." ]
bc77d6ddb768c0d2fd57bc806ae60468067978f9
https://github.com/jaredLunde/react-broker/blob/bc77d6ddb768c0d2fd57bc806ae60468067978f9/src/macro/index.js#L20-L59
train
jaredLunde/react-broker
src/macro/index.js
toObjectExpression
function toObjectExpression (obj, {types: t, template}) { const properties = [] for (let key in obj) { properties.push(t.objectProperty(t.stringLiteral(key), obj[key])) } return t.objectExpression(properties) }
javascript
function toObjectExpression (obj, {types: t, template}) { const properties = [] for (let key in obj) { properties.push(t.objectProperty(t.stringLiteral(key), obj[key])) } return t.objectExpression(properties) }
[ "function", "toObjectExpression", "(", "obj", ",", "{", "types", ":", "t", ",", "template", "}", ")", "{", "const", "properties", "=", "[", "]", "for", "(", "let", "key", "in", "obj", ")", "{", "properties", ".", "push", "(", "t", ".", "objectProperty", "(", "t", ".", "stringLiteral", "(", "key", ")", ",", "obj", "[", "key", "]", ")", ")", "}", "return", "t", ".", "objectExpression", "(", "properties", ")", "}" ]
creates a Babel object expression from a Javascript object with string keys
[ "creates", "a", "Babel", "object", "expression", "from", "a", "Javascript", "object", "with", "string", "keys" ]
bc77d6ddb768c0d2fd57bc806ae60468067978f9
https://github.com/jaredLunde/react-broker/blob/bc77d6ddb768c0d2fd57bc806ae60468067978f9/src/macro/index.js#L63-L71
train
jaredLunde/react-broker
src/macro/index.js
getShortChunkName
function getShortChunkName (source) { if (source.match(relativePkg) || path.isAbsolute(source)) { return path.dirname(source).split(path.sep).slice(-2).join('/') + '/' + path.basename(source) } else { return source } }
javascript
function getShortChunkName (source) { if (source.match(relativePkg) || path.isAbsolute(source)) { return path.dirname(source).split(path.sep).slice(-2).join('/') + '/' + path.basename(source) } else { return source } }
[ "function", "getShortChunkName", "(", "source", ")", "{", "if", "(", "source", ".", "match", "(", "relativePkg", ")", "||", "path", ".", "isAbsolute", "(", "source", ")", ")", "{", "return", "path", ".", "dirname", "(", "source", ")", ".", "split", "(", "path", ".", "sep", ")", ".", "slice", "(", "-", "2", ")", ".", "join", "(", "'/'", ")", "+", "'/'", "+", "path", ".", "basename", "(", "source", ")", "}", "else", "{", "return", "source", "}", "}" ]
shortens the chunk name to its parent directory basename and its basename
[ "shortens", "the", "chunk", "name", "to", "its", "parent", "directory", "basename", "and", "its", "basename" ]
bc77d6ddb768c0d2fd57bc806ae60468067978f9
https://github.com/jaredLunde/react-broker/blob/bc77d6ddb768c0d2fd57bc806ae60468067978f9/src/macro/index.js#L135-L142
train
emeryrose/konduit
lib/pipeline.js
function(options) { stream.Duplex.call(this, { objectMode: true }); this.options = extend(true, Pipeline.DEFAULTS, options || {}); this.readyState = 0; // 0: closed, 1: open this._pipeline = []; this.setMaxListeners(0); // unlimited listeners allowed this.options.ipc.subscribe( this.options.ipc.namespace, this._proxy.bind(this) ); }
javascript
function(options) { stream.Duplex.call(this, { objectMode: true }); this.options = extend(true, Pipeline.DEFAULTS, options || {}); this.readyState = 0; // 0: closed, 1: open this._pipeline = []; this.setMaxListeners(0); // unlimited listeners allowed this.options.ipc.subscribe( this.options.ipc.namespace, this._proxy.bind(this) ); }
[ "function", "(", "options", ")", "{", "stream", ".", "Duplex", ".", "call", "(", "this", ",", "{", "objectMode", ":", "true", "}", ")", ";", "this", ".", "options", "=", "extend", "(", "true", ",", "Pipeline", ".", "DEFAULTS", ",", "options", "||", "{", "}", ")", ";", "this", ".", "readyState", "=", "0", ";", "this", ".", "_pipeline", "=", "[", "]", ";", "this", ".", "setMaxListeners", "(", "0", ")", ";", "this", ".", "options", ".", "ipc", ".", "subscribe", "(", "this", ".", "options", ".", "ipc", ".", "namespace", ",", "this", ".", "_proxy", ".", "bind", "(", "this", ")", ")", ";", "}" ]
A stream of "activities" that flow through a handler pipeline. @constructor @param {object} options - a configuration object
[ "A", "stream", "of", "activities", "that", "flow", "through", "a", "handler", "pipeline", "." ]
6fcd6d4d0191b2ba42834f807cc62b9f607306d8
https://github.com/emeryrose/konduit/blob/6fcd6d4d0191b2ba42834f807cc62b9f607306d8/lib/pipeline.js#L16-L30
train
bahmutov/connect-slow
index.js
getQueryDelay
function getQueryDelay(url) { var delay; if (options.delayQueryParam) { var parsedUrl = parseUrl(url, true); if (parsedUrl.query && parsedUrl.query[options.delayQueryParam]) { var queryDelay = parseInt(parsedUrl.query[options.delayQueryParam]); if (queryDelay > 0) { delay = queryDelay; } } } return delay; }
javascript
function getQueryDelay(url) { var delay; if (options.delayQueryParam) { var parsedUrl = parseUrl(url, true); if (parsedUrl.query && parsedUrl.query[options.delayQueryParam]) { var queryDelay = parseInt(parsedUrl.query[options.delayQueryParam]); if (queryDelay > 0) { delay = queryDelay; } } } return delay; }
[ "function", "getQueryDelay", "(", "url", ")", "{", "var", "delay", ";", "if", "(", "options", ".", "delayQueryParam", ")", "{", "var", "parsedUrl", "=", "parseUrl", "(", "url", ",", "true", ")", ";", "if", "(", "parsedUrl", ".", "query", "&&", "parsedUrl", ".", "query", "[", "options", ".", "delayQueryParam", "]", ")", "{", "var", "queryDelay", "=", "parseInt", "(", "parsedUrl", ".", "query", "[", "options", ".", "delayQueryParam", "]", ")", ";", "if", "(", "queryDelay", ">", "0", ")", "{", "delay", "=", "queryDelay", ";", "}", "}", "}", "return", "delay", ";", "}" ]
Return the query delay if it makes sense for this request, else undefined
[ "Return", "the", "query", "delay", "if", "it", "makes", "sense", "for", "this", "request", "else", "undefined" ]
8a8ca741f56c041792f6871f87556ef1f55ae752
https://github.com/bahmutov/connect-slow/blob/8a8ca741f56c041792f6871f87556ef1f55ae752/index.js#L20-L34
train
bahmutov/connect-slow
index.js
getUrlDelay
function getUrlDelay(url) { var delay; if (options.url && !options.url.test(url)) { delay = 0; } return delay; }
javascript
function getUrlDelay(url) { var delay; if (options.url && !options.url.test(url)) { delay = 0; } return delay; }
[ "function", "getUrlDelay", "(", "url", ")", "{", "var", "delay", ";", "if", "(", "options", ".", "url", "&&", "!", "options", ".", "url", ".", "test", "(", "url", ")", ")", "{", "delay", "=", "0", ";", "}", "return", "delay", ";", "}" ]
Return the url delay if it makes sense for this request, else undefined
[ "Return", "the", "url", "delay", "if", "it", "makes", "sense", "for", "this", "request", "else", "undefined" ]
8a8ca741f56c041792f6871f87556ef1f55ae752
https://github.com/bahmutov/connect-slow/blob/8a8ca741f56c041792f6871f87556ef1f55ae752/index.js#L37-L44
train
littlebits/cloud-client-api-http
lib/make-method.js
todo_name_me
function todo_name_me() { var args = process_signature(arguments) var opts = merge({}, base_defaults, args.overrides) return f.apply(null, [opts, args.cb]) }
javascript
function todo_name_me() { var args = process_signature(arguments) var opts = merge({}, base_defaults, args.overrides) return f.apply(null, [opts, args.cb]) }
[ "function", "todo_name_me", "(", ")", "{", "var", "args", "=", "process_signature", "(", "arguments", ")", "var", "opts", "=", "merge", "(", "{", "}", ",", "base_defaults", ",", "args", ".", "overrides", ")", "return", "f", ".", "apply", "(", "null", ",", "[", "opts", ",", "args", ".", "cb", "]", ")", "}" ]
Give this function a better name. We could accept a name parameter and create the function using Function constructor.
[ "Give", "this", "function", "a", "better", "name", ".", "We", "could", "accept", "a", "name", "parameter", "and", "create", "the", "function", "using", "Function", "constructor", "." ]
d7bd5e31ee95873ce644f9526f5459483f67988b
https://github.com/littlebits/cloud-client-api-http/blob/d7bd5e31ee95873ce644f9526f5459483f67988b/lib/make-method.js#L12-L16
train
lgeiger/escape-carriage
index.js
escapeCarriageReturn
function escapeCarriageReturn(txt) { if (!txt) return ""; if (!/\r/.test(txt)) return txt; txt = txt.replace(/\r+\n/gm, "\n"); // \r followed by \n --> newline while (/\r[^$]/.test(txt)) { var base = /^(.*)\r+/m.exec(txt)[1]; var insert = /\r+(.*)$/m.exec(txt)[1]; insert = insert + base.slice(insert.length, base.length); txt = txt.replace(/\r+.*$/m, "\r").replace(/^.*\r/m, insert); } return txt; }
javascript
function escapeCarriageReturn(txt) { if (!txt) return ""; if (!/\r/.test(txt)) return txt; txt = txt.replace(/\r+\n/gm, "\n"); // \r followed by \n --> newline while (/\r[^$]/.test(txt)) { var base = /^(.*)\r+/m.exec(txt)[1]; var insert = /\r+(.*)$/m.exec(txt)[1]; insert = insert + base.slice(insert.length, base.length); txt = txt.replace(/\r+.*$/m, "\r").replace(/^.*\r/m, insert); } return txt; }
[ "function", "escapeCarriageReturn", "(", "txt", ")", "{", "if", "(", "!", "txt", ")", "return", "\"\"", ";", "if", "(", "!", "/", "\\r", "/", ".", "test", "(", "txt", ")", ")", "return", "txt", ";", "txt", "=", "txt", ".", "replace", "(", "/", "\\r+\\n", "/", "gm", ",", "\"\\n\"", ")", ";", "\\n", "while", "(", "/", "\\r[^$]", "/", ".", "test", "(", "txt", ")", ")", "{", "var", "base", "=", "/", "^(.*)\\r+", "/", "m", ".", "exec", "(", "txt", ")", "[", "1", "]", ";", "var", "insert", "=", "/", "\\r+(.*)$", "/", "m", ".", "exec", "(", "txt", ")", "[", "1", "]", ";", "insert", "=", "insert", "+", "base", ".", "slice", "(", "insert", ".", "length", ",", "base", ".", "length", ")", ";", "txt", "=", "txt", ".", "replace", "(", "/", "\\r+.*$", "/", "m", ",", "\"\\r\"", ")", ".", "\\r", "replace", ";", "}", "}" ]
Escape carrigage returns like a terminal @param {string} txt - String to escape. @return {string} - Escaped string.
[ "Escape", "carrigage", "returns", "like", "a", "terminal" ]
fb4fcdfd11745cf654909f87c557e662b827351b
https://github.com/lgeiger/escape-carriage/blob/fb4fcdfd11745cf654909f87c557e662b827351b/index.js#L6-L17
train
lgeiger/escape-carriage
index.js
escapeCarriageReturnSafe
function escapeCarriageReturnSafe(txt) { if (!txt) return ""; if (!/\r/.test(txt)) return txt; if (!/\n/.test(txt)) return escapeSingleLineSafe(txt); txt = txt.replace(/\r+\n/gm, "\n"); // \r followed by \n --> newline var idx = txt.lastIndexOf("\n"); return ( escapeCarriageReturn(txt.slice(0, idx)) + "\n" + escapeSingleLineSafe(txt.slice(idx + 1)) ); }
javascript
function escapeCarriageReturnSafe(txt) { if (!txt) return ""; if (!/\r/.test(txt)) return txt; if (!/\n/.test(txt)) return escapeSingleLineSafe(txt); txt = txt.replace(/\r+\n/gm, "\n"); // \r followed by \n --> newline var idx = txt.lastIndexOf("\n"); return ( escapeCarriageReturn(txt.slice(0, idx)) + "\n" + escapeSingleLineSafe(txt.slice(idx + 1)) ); }
[ "function", "escapeCarriageReturnSafe", "(", "txt", ")", "{", "if", "(", "!", "txt", ")", "return", "\"\"", ";", "if", "(", "!", "/", "\\r", "/", ".", "test", "(", "txt", ")", ")", "return", "txt", ";", "if", "(", "!", "/", "\\n", "/", ".", "test", "(", "txt", ")", ")", "return", "escapeSingleLineSafe", "(", "txt", ")", ";", "txt", "=", "txt", ".", "replace", "(", "/", "\\r+\\n", "/", "gm", ",", "\"\\n\"", ")", ";", "\\n", "var", "idx", "=", "txt", ".", "lastIndexOf", "(", "\"\\n\"", ")", ";", "}" ]
Safely escape carrigage returns like a terminal. This allows to escape carrigage returns while allowing future output to be appended without loosing information. Use this as a intermediate escape step if your stream hasn't completed yet. @param {string} txt - String to escape. @return {string} - Escaped string.
[ "Safely", "escape", "carrigage", "returns", "like", "a", "terminal", ".", "This", "allows", "to", "escape", "carrigage", "returns", "while", "allowing", "future", "output", "to", "be", "appended", "without", "loosing", "information", ".", "Use", "this", "as", "a", "intermediate", "escape", "step", "if", "your", "stream", "hasn", "t", "completed", "yet", "." ]
fb4fcdfd11745cf654909f87c557e662b827351b
https://github.com/lgeiger/escape-carriage/blob/fb4fcdfd11745cf654909f87c557e662b827351b/index.js#L51-L63
train
LaunchPadLab/lp-redux-api
src/middleware/parse-action.js
parseAction
function parseAction ({ action, payload={}, error=false }) { switch (typeof action) { // If it's an action creator, create the action case 'function': return action(payload) // If it's an action object return the action case 'object': return action // Otherwise, create a "default" action object with the given type case 'string': return { type: action, payload, error } default: throw new Error('Invalid action definition (must be function, object or string).') } }
javascript
function parseAction ({ action, payload={}, error=false }) { switch (typeof action) { // If it's an action creator, create the action case 'function': return action(payload) // If it's an action object return the action case 'object': return action // Otherwise, create a "default" action object with the given type case 'string': return { type: action, payload, error } default: throw new Error('Invalid action definition (must be function, object or string).') } }
[ "function", "parseAction", "(", "{", "action", ",", "payload", "=", "{", "}", ",", "error", "=", "false", "}", ")", "{", "switch", "(", "typeof", "action", ")", "{", "case", "'function'", ":", "return", "action", "(", "payload", ")", "case", "'object'", ":", "return", "action", "case", "'string'", ":", "return", "{", "type", ":", "action", ",", "payload", ",", "error", "}", "default", ":", "throw", "new", "Error", "(", "'Invalid action definition (must be function, object or string).'", ")", "}", "}" ]
Create an action from an action "definition."
[ "Create", "an", "action", "from", "an", "action", "definition", "." ]
73eee231067365326780ddc1dbbfa50d3e65defc
https://github.com/LaunchPadLab/lp-redux-api/blob/73eee231067365326780ddc1dbbfa50d3e65defc/src/middleware/parse-action.js#L2-L12
train
RetailMeNotSandbox/roux
lib/pantry.js
Pantry
function Pantry(config) { this.name = config.name; this.path = config.path; this.ingredients = _.clone(config.ingredients); }
javascript
function Pantry(config) { this.name = config.name; this.path = config.path; this.ingredients = _.clone(config.ingredients); }
[ "function", "Pantry", "(", "config", ")", "{", "this", ".", "name", "=", "config", ".", "name", ";", "this", ".", "path", "=", "config", ".", "path", ";", "this", ".", "ingredients", "=", "_", ".", "clone", "(", "config", ".", "ingredients", ")", ";", "}" ]
Interface to a pantry of Roux ingredients @param {Object} config - Pantry configuration @param {string} config.path - the path to the pantry @param {string} config.name - the name of the pantry @param {Ingredient} config.ingredients - the ingredients in the pantry
[ "Interface", "to", "a", "pantry", "of", "Roux", "ingredients" ]
519616c4deeb47545da44098767e71dfd10a0e83
https://github.com/RetailMeNotSandbox/roux/blob/519616c4deeb47545da44098767e71dfd10a0e83/lib/pantry.js#L14-L19
train
zaim/immpatch
src/parse.js
parsePointer
function parsePointer (pointer) { if (pointer === '') { return [] } if (pointer.charAt(0) !== '/') { throw new error.PointerError('Invalid JSON pointer: ' + pointer) } return pointer.substring(1).split(/\//).map(unescape) }
javascript
function parsePointer (pointer) { if (pointer === '') { return [] } if (pointer.charAt(0) !== '/') { throw new error.PointerError('Invalid JSON pointer: ' + pointer) } return pointer.substring(1).split(/\//).map(unescape) }
[ "function", "parsePointer", "(", "pointer", ")", "{", "if", "(", "pointer", "===", "''", ")", "{", "return", "[", "]", "}", "if", "(", "pointer", ".", "charAt", "(", "0", ")", "!==", "'/'", ")", "{", "throw", "new", "error", ".", "PointerError", "(", "'Invalid JSON pointer: '", "+", "pointer", ")", "}", "return", "pointer", ".", "substring", "(", "1", ")", ".", "split", "(", "/", "\\/", "/", ")", ".", "map", "(", "unescape", ")", "}" ]
Convert a JSON Pointer into a key path array @private @param {string} pointer @returns {array}
[ "Convert", "a", "JSON", "Pointer", "into", "a", "key", "path", "array" ]
039647d10506bc928f95c962f7cd5950574637e8
https://github.com/zaim/immpatch/blob/039647d10506bc928f95c962f7cd5950574637e8/src/parse.js#L30-L38
train
zaim/immpatch
src/parse.js
validatePath
function validatePath (path, target) { var i = 0 var len = path.length var ref = target for (; i < len; i++) { if (Iterable.isIterable(ref)) { ref = ref.getIn(path.slice(0, i)) if (Iterable.isIndexed(ref) && !validateIndexToken(path[i])) { throw new error.PointerError('Invalid array index: ' + path[i]) } } } }
javascript
function validatePath (path, target) { var i = 0 var len = path.length var ref = target for (; i < len; i++) { if (Iterable.isIterable(ref)) { ref = ref.getIn(path.slice(0, i)) if (Iterable.isIndexed(ref) && !validateIndexToken(path[i])) { throw new error.PointerError('Invalid array index: ' + path[i]) } } } }
[ "function", "validatePath", "(", "path", ",", "target", ")", "{", "var", "i", "=", "0", "var", "len", "=", "path", ".", "length", "var", "ref", "=", "target", "for", "(", ";", "i", "<", "len", ";", "i", "++", ")", "{", "if", "(", "Iterable", ".", "isIterable", "(", "ref", ")", ")", "{", "ref", "=", "ref", ".", "getIn", "(", "path", ".", "slice", "(", "0", ",", "i", ")", ")", "if", "(", "Iterable", ".", "isIndexed", "(", "ref", ")", "&&", "!", "validateIndexToken", "(", "path", "[", "i", "]", ")", ")", "{", "throw", "new", "error", ".", "PointerError", "(", "'Invalid array index: '", "+", "path", "[", "i", "]", ")", "}", "}", "}", "}" ]
Validate key path @private @param {array} path @param {Immutable} target @throws PatchError
[ "Validate", "key", "path" ]
039647d10506bc928f95c962f7cd5950574637e8
https://github.com/zaim/immpatch/blob/039647d10506bc928f95c962f7cd5950574637e8/src/parse.js#L50-L62
train
coditorium/gulp-html-lint
lib/index.js
gulpHtmlLint
function gulpHtmlLint(options) { let htmlLintOptions = {}, issueFileCount = 0, issueCount = 0; options = options || {}; options.htmllintrc = options.htmllintrc || '.htmllintrc'; options.useHtmllintrc = options.useHtmllintrc !== false; options.plugins = options.plugins || []; options.limitFiles = options.limitFiles || (options.bail ? 1 : Number.MAX_VALUE); options.limitIssuesPerFile = options.limitIssuesPerFile || Number.MAX_VALUE; options.limitIssues = options.limitIssues || Number.MAX_VALUE; // load htmllint rules if (options.useHtmllintrc && fs.existsSync(options.htmllintrc)) { htmlLintOptions = JSON.parse(fs.readFileSync(options.htmllintrc, 'utf8')); } if (options.rules && typeof options.rules === 'object') { Object.keys(options.rules).forEach((prop) => { htmlLintOptions[prop] = options.rules[prop]; }); } // use plugins htmllint.use(options.plugins); return transform((file, enc, cb) => { if (file.isNull()) return cb(null, file); if (file.isStream()) return cb(new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported')); if (issueFileCount >= options.limitFiles || issueCount >= options.limitIssues) return cb(null, file); const relativeFilePath = path.relative(process.cwd(), file.path); htmllint(file.contents.toString(), htmlLintOptions) .then((issues) => { if (issues && issues.length) { let errorCount = 0, warningCount = 0; issueFileCount++; issueCount += issues.length; issues.forEach((issue) => { if (issue.code.indexOf('E') === 0) { issue.error = true; errorCount++; } else { issue.error = false; warningCount++; } issue.warning = !issue.error; issue.message = issue.message || htmllint.messages.renderIssue(issue); }); file.htmlLint = { filePath: file.path, issues: issues.splice(0, Math.min(issues.length, options.limitIssuesPerFile)), relativeFilePath, errorCount, warningCount }; } cb(null, file); }, () => { return cb(new gutil.PluginError(PLUGIN_NAME, `Could not lint html file: ${relativeFilePath}`)); }); }); }
javascript
function gulpHtmlLint(options) { let htmlLintOptions = {}, issueFileCount = 0, issueCount = 0; options = options || {}; options.htmllintrc = options.htmllintrc || '.htmllintrc'; options.useHtmllintrc = options.useHtmllintrc !== false; options.plugins = options.plugins || []; options.limitFiles = options.limitFiles || (options.bail ? 1 : Number.MAX_VALUE); options.limitIssuesPerFile = options.limitIssuesPerFile || Number.MAX_VALUE; options.limitIssues = options.limitIssues || Number.MAX_VALUE; // load htmllint rules if (options.useHtmllintrc && fs.existsSync(options.htmllintrc)) { htmlLintOptions = JSON.parse(fs.readFileSync(options.htmllintrc, 'utf8')); } if (options.rules && typeof options.rules === 'object') { Object.keys(options.rules).forEach((prop) => { htmlLintOptions[prop] = options.rules[prop]; }); } // use plugins htmllint.use(options.plugins); return transform((file, enc, cb) => { if (file.isNull()) return cb(null, file); if (file.isStream()) return cb(new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported')); if (issueFileCount >= options.limitFiles || issueCount >= options.limitIssues) return cb(null, file); const relativeFilePath = path.relative(process.cwd(), file.path); htmllint(file.contents.toString(), htmlLintOptions) .then((issues) => { if (issues && issues.length) { let errorCount = 0, warningCount = 0; issueFileCount++; issueCount += issues.length; issues.forEach((issue) => { if (issue.code.indexOf('E') === 0) { issue.error = true; errorCount++; } else { issue.error = false; warningCount++; } issue.warning = !issue.error; issue.message = issue.message || htmllint.messages.renderIssue(issue); }); file.htmlLint = { filePath: file.path, issues: issues.splice(0, Math.min(issues.length, options.limitIssuesPerFile)), relativeFilePath, errorCount, warningCount }; } cb(null, file); }, () => { return cb(new gutil.PluginError(PLUGIN_NAME, `Could not lint html file: ${relativeFilePath}`)); }); }); }
[ "function", "gulpHtmlLint", "(", "options", ")", "{", "let", "htmlLintOptions", "=", "{", "}", ",", "issueFileCount", "=", "0", ",", "issueCount", "=", "0", ";", "options", "=", "options", "||", "{", "}", ";", "options", ".", "htmllintrc", "=", "options", ".", "htmllintrc", "||", "'.htmllintrc'", ";", "options", ".", "useHtmllintrc", "=", "options", ".", "useHtmllintrc", "!==", "false", ";", "options", ".", "plugins", "=", "options", ".", "plugins", "||", "[", "]", ";", "options", ".", "limitFiles", "=", "options", ".", "limitFiles", "||", "(", "options", ".", "bail", "?", "1", ":", "Number", ".", "MAX_VALUE", ")", ";", "options", ".", "limitIssuesPerFile", "=", "options", ".", "limitIssuesPerFile", "||", "Number", ".", "MAX_VALUE", ";", "options", ".", "limitIssues", "=", "options", ".", "limitIssues", "||", "Number", ".", "MAX_VALUE", ";", "if", "(", "options", ".", "useHtmllintrc", "&&", "fs", ".", "existsSync", "(", "options", ".", "htmllintrc", ")", ")", "{", "htmlLintOptions", "=", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "options", ".", "htmllintrc", ",", "'utf8'", ")", ")", ";", "}", "if", "(", "options", ".", "rules", "&&", "typeof", "options", ".", "rules", "===", "'object'", ")", "{", "Object", ".", "keys", "(", "options", ".", "rules", ")", ".", "forEach", "(", "(", "prop", ")", "=>", "{", "htmlLintOptions", "[", "prop", "]", "=", "options", ".", "rules", "[", "prop", "]", ";", "}", ")", ";", "}", "htmllint", ".", "use", "(", "options", ".", "plugins", ")", ";", "return", "transform", "(", "(", "file", ",", "enc", ",", "cb", ")", "=>", "{", "if", "(", "file", ".", "isNull", "(", ")", ")", "return", "cb", "(", "null", ",", "file", ")", ";", "if", "(", "file", ".", "isStream", "(", ")", ")", "return", "cb", "(", "new", "gutil", ".", "PluginError", "(", "PLUGIN_NAME", ",", "'Streaming not supported'", ")", ")", ";", "if", "(", "issueFileCount", ">=", "options", ".", "limitFiles", "||", "issueCount", ">=", "options", ".", "limitIssues", ")", "return", "cb", "(", "null", ",", "file", ")", ";", "const", "relativeFilePath", "=", "path", ".", "relative", "(", "process", ".", "cwd", "(", ")", ",", "file", ".", "path", ")", ";", "htmllint", "(", "file", ".", "contents", ".", "toString", "(", ")", ",", "htmlLintOptions", ")", ".", "then", "(", "(", "issues", ")", "=>", "{", "if", "(", "issues", "&&", "issues", ".", "length", ")", "{", "let", "errorCount", "=", "0", ",", "warningCount", "=", "0", ";", "issueFileCount", "++", ";", "issueCount", "+=", "issues", ".", "length", ";", "issues", ".", "forEach", "(", "(", "issue", ")", "=>", "{", "if", "(", "issue", ".", "code", ".", "indexOf", "(", "'E'", ")", "===", "0", ")", "{", "issue", ".", "error", "=", "true", ";", "errorCount", "++", ";", "}", "else", "{", "issue", ".", "error", "=", "false", ";", "warningCount", "++", ";", "}", "issue", ".", "warning", "=", "!", "issue", ".", "error", ";", "issue", ".", "message", "=", "issue", ".", "message", "||", "htmllint", ".", "messages", ".", "renderIssue", "(", "issue", ")", ";", "}", ")", ";", "file", ".", "htmlLint", "=", "{", "filePath", ":", "file", ".", "path", ",", "issues", ":", "issues", ".", "splice", "(", "0", ",", "Math", ".", "min", "(", "issues", ".", "length", ",", "options", ".", "limitIssuesPerFile", ")", ")", ",", "relativeFilePath", ",", "errorCount", ",", "warningCount", "}", ";", "}", "cb", "(", "null", ",", "file", ")", ";", "}", ",", "(", ")", "=>", "{", "return", "cb", "(", "new", "gutil", ".", "PluginError", "(", "PLUGIN_NAME", ",", "`", "${", "relativeFilePath", "}", "`", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Append HtmlLint result to each file in gulp stream. @param {(Object|String)} [options] - Configure rules, plugins and other options for running HtmlLint @returns {stream} gulp file stream
[ "Append", "HtmlLint", "result", "to", "each", "file", "in", "gulp", "stream", "." ]
a403ab7f8a7f13fe439f6035bc3a5e49deca3d98
https://github.com/coditorium/gulp-html-lint/blob/a403ab7f8a7f13fe439f6035bc3a5e49deca3d98/lib/index.js#L17-L80
train
coditorium/gulp-html-lint
lib/index.js
tryResultAction
function tryResultAction(action, result, callback) { if (action.length > 1) return action.call(this, result, callback); try { action.call(this, result); } catch (err) { return callback(err || new Error('Unknown Error')); } return callback(); }
javascript
function tryResultAction(action, result, callback) { if (action.length > 1) return action.call(this, result, callback); try { action.call(this, result); } catch (err) { return callback(err || new Error('Unknown Error')); } return callback(); }
[ "function", "tryResultAction", "(", "action", ",", "result", ",", "callback", ")", "{", "if", "(", "action", ".", "length", ">", "1", ")", "return", "action", ".", "call", "(", "this", ",", "result", ",", "callback", ")", ";", "try", "{", "action", ".", "call", "(", "this", ",", "result", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "callback", "(", "err", "||", "new", "Error", "(", "'Unknown Error'", ")", ")", ";", "}", "return", "callback", "(", ")", ";", "}" ]
Call sync or async action and handle any thrown or async error @param {Function} action - Result action to call @param {(Object|Array)} result - An HtmlLint result or result list @param {Function} callback - An callback for when the action is complete @returns {undefined}
[ "Call", "sync", "or", "async", "action", "and", "handle", "any", "thrown", "or", "async", "error" ]
a403ab7f8a7f13fe439f6035bc3a5e49deca3d98
https://github.com/coditorium/gulp-html-lint/blob/a403ab7f8a7f13fe439f6035bc3a5e49deca3d98/lib/index.js#L209-L217
train
coditorium/gulp-html-lint
lib/index.js
wrapError
function wrapError(err) { if (err && !(err instanceof gutil.PluginError)) { err = new PluginError(err.plugin || PLUGIN_NAME, err, { showStack: (err.showStack !== false) }); } return err; }
javascript
function wrapError(err) { if (err && !(err instanceof gutil.PluginError)) { err = new PluginError(err.plugin || PLUGIN_NAME, err, { showStack: (err.showStack !== false) }); } return err; }
[ "function", "wrapError", "(", "err", ")", "{", "if", "(", "err", "&&", "!", "(", "err", "instanceof", "gutil", ".", "PluginError", ")", ")", "{", "err", "=", "new", "PluginError", "(", "err", ".", "plugin", "||", "PLUGIN_NAME", ",", "err", ",", "{", "showStack", ":", "(", "err", ".", "showStack", "!==", "false", ")", "}", ")", ";", "}", "return", "err", ";", "}" ]
Ensure that error is wrapped in a gulp PluginError @param {Object} err - An error to be wrapped @returns {Object} A wrapped error
[ "Ensure", "that", "error", "is", "wrapped", "in", "a", "gulp", "PluginError" ]
a403ab7f8a7f13fe439f6035bc3a5e49deca3d98
https://github.com/coditorium/gulp-html-lint/blob/a403ab7f8a7f13fe439f6035bc3a5e49deca3d98/lib/index.js#L225-L232
train
coditorium/gulp-html-lint
lib/index.js
resolveFormatter
function resolveFormatter(formatter) { if (!formatter) return resolveFormatter('stylish'); if (typeof formatter === 'function') return formatter; if (typeof formatter === 'string') { if (isModuleAvailable(formatter)) return require(formatter); if (isModuleAvailable(`./formatters/${formatter}`)) return require(`./formatters/${formatter}`); throw wrapError(new Error(`Could not resolve formatter: ${formatter}`)); } }
javascript
function resolveFormatter(formatter) { if (!formatter) return resolveFormatter('stylish'); if (typeof formatter === 'function') return formatter; if (typeof formatter === 'string') { if (isModuleAvailable(formatter)) return require(formatter); if (isModuleAvailable(`./formatters/${formatter}`)) return require(`./formatters/${formatter}`); throw wrapError(new Error(`Could not resolve formatter: ${formatter}`)); } }
[ "function", "resolveFormatter", "(", "formatter", ")", "{", "if", "(", "!", "formatter", ")", "return", "resolveFormatter", "(", "'stylish'", ")", ";", "if", "(", "typeof", "formatter", "===", "'function'", ")", "return", "formatter", ";", "if", "(", "typeof", "formatter", "===", "'string'", ")", "{", "if", "(", "isModuleAvailable", "(", "formatter", ")", ")", "return", "require", "(", "formatter", ")", ";", "if", "(", "isModuleAvailable", "(", "`", "${", "formatter", "}", "`", ")", ")", "return", "require", "(", "`", "${", "formatter", "}", "`", ")", ";", "throw", "wrapError", "(", "new", "Error", "(", "`", "${", "formatter", "}", "`", ")", ")", ";", "}", "}" ]
Resolves formatter. @param {string|function} formatter - formatter @returns {function} formatter function
[ "Resolves", "formatter", "." ]
a403ab7f8a7f13fe439f6035bc3a5e49deca3d98
https://github.com/coditorium/gulp-html-lint/blob/a403ab7f8a7f13fe439f6035bc3a5e49deca3d98/lib/index.js#L240-L248
train
axke/rs-api
lib/util/jsonp.js
function (obj) { var keys = [] for (var key in obj) { if (obj.hasOwnProperty(key)) { keys.push(key) } } return keys }
javascript
function (obj) { var keys = [] for (var key in obj) { if (obj.hasOwnProperty(key)) { keys.push(key) } } return keys }
[ "function", "(", "obj", ")", "{", "var", "keys", "=", "[", "]", "for", "(", "var", "key", "in", "obj", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "keys", ".", "push", "(", "key", ")", "}", "}", "return", "keys", "}" ]
Gets all the keys that belong to an object
[ "Gets", "all", "the", "keys", "that", "belong", "to", "an", "object" ]
71af4973e1d079f09b7d888b6d24735784185942
https://github.com/axke/rs-api/blob/71af4973e1d079f09b7d888b6d24735784185942/lib/util/jsonp.js#L50-L58
train
kibertoad/validation-utils
lib/validation.helper.js
lessThan
function lessThan(validatedObject, threshold, errorText) { number(validatedObject); number(threshold, 'Threshold is not a number'); if (validatedObject >= threshold) { throw new ValidationError( errorText || `Validated number ${validatedObject} is not less than the threshold ${threshold}` ); } return validatedObject; }
javascript
function lessThan(validatedObject, threshold, errorText) { number(validatedObject); number(threshold, 'Threshold is not a number'); if (validatedObject >= threshold) { throw new ValidationError( errorText || `Validated number ${validatedObject} is not less than the threshold ${threshold}` ); } return validatedObject; }
[ "function", "lessThan", "(", "validatedObject", ",", "threshold", ",", "errorText", ")", "{", "number", "(", "validatedObject", ")", ";", "number", "(", "threshold", ",", "'Threshold is not a number'", ")", ";", "if", "(", "validatedObject", ">=", "threshold", ")", "{", "throw", "new", "ValidationError", "(", "errorText", "||", "`", "${", "validatedObject", "}", "${", "threshold", "}", "`", ")", ";", "}", "return", "validatedObject", ";", "}" ]
Checks value to be a number that is less than the specified number @param {*} validatedObject @param {number} threshold - if validated number is equal or larger than this, throw an error @param {String} [errorText] - message for error thrown if validation fails @returns {number} validatedObject
[ "Checks", "value", "to", "be", "a", "number", "that", "is", "less", "than", "the", "specified", "number" ]
6cc2a41e9dd6407f29986ed605840d30234802d6
https://github.com/kibertoad/validation-utils/blob/6cc2a41e9dd6407f29986ed605840d30234802d6/lib/validation.helper.js#L64-L73
train
kibertoad/validation-utils
lib/validation.helper.js
greaterThan
function greaterThan(validatedObject, threshold, errorText) { number(validatedObject); number(threshold, 'Threshold is not a number'); if (validatedObject <= threshold) { throw new ValidationError( errorText || `Validated number ${validatedObject} is not greater than the threshold ${threshold}` ); } return validatedObject; }
javascript
function greaterThan(validatedObject, threshold, errorText) { number(validatedObject); number(threshold, 'Threshold is not a number'); if (validatedObject <= threshold) { throw new ValidationError( errorText || `Validated number ${validatedObject} is not greater than the threshold ${threshold}` ); } return validatedObject; }
[ "function", "greaterThan", "(", "validatedObject", ",", "threshold", ",", "errorText", ")", "{", "number", "(", "validatedObject", ")", ";", "number", "(", "threshold", ",", "'Threshold is not a number'", ")", ";", "if", "(", "validatedObject", "<=", "threshold", ")", "{", "throw", "new", "ValidationError", "(", "errorText", "||", "`", "${", "validatedObject", "}", "${", "threshold", "}", "`", ")", ";", "}", "return", "validatedObject", ";", "}" ]
Checks value to be a number that is greater than specified number @param {*} validatedObject @param {number} threshold - if validated number is equal or less than this, throw an error @param {String} [errorText] - message for error thrown if validation fails @returns {number} validatedObject
[ "Checks", "value", "to", "be", "a", "number", "that", "is", "greater", "than", "specified", "number" ]
6cc2a41e9dd6407f29986ed605840d30234802d6
https://github.com/kibertoad/validation-utils/blob/6cc2a41e9dd6407f29986ed605840d30234802d6/lib/validation.helper.js#L82-L92
train
kibertoad/validation-utils
lib/validation.helper.js
booleanTrue
function booleanTrue(validatedObject, errorText) { if (!_.isBoolean(validatedObject) || !validatedObject) { throw new ValidationError(errorText || 'Validated object is not True'); } return validatedObject; }
javascript
function booleanTrue(validatedObject, errorText) { if (!_.isBoolean(validatedObject) || !validatedObject) { throw new ValidationError(errorText || 'Validated object is not True'); } return validatedObject; }
[ "function", "booleanTrue", "(", "validatedObject", ",", "errorText", ")", "{", "if", "(", "!", "_", ".", "isBoolean", "(", "validatedObject", ")", "||", "!", "validatedObject", ")", "{", "throw", "new", "ValidationError", "(", "errorText", "||", "'Validated object is not True'", ")", ";", "}", "return", "validatedObject", ";", "}" ]
Checks value to be a True boolean @param {*} validatedObject @param {String} [errorText] - message for error thrown if validation fails @returns {boolean} validatedObject
[ "Checks", "value", "to", "be", "a", "True", "boolean" ]
6cc2a41e9dd6407f29986ed605840d30234802d6
https://github.com/kibertoad/validation-utils/blob/6cc2a41e9dd6407f29986ed605840d30234802d6/lib/validation.helper.js#L143-L148
train
kibertoad/validation-utils
lib/validation.helper.js
booleanFalse
function booleanFalse(validatedObject, errorText) { if (!_.isBoolean(validatedObject) || validatedObject) { throw new ValidationError(errorText || 'Validated object is not False'); } return validatedObject; }
javascript
function booleanFalse(validatedObject, errorText) { if (!_.isBoolean(validatedObject) || validatedObject) { throw new ValidationError(errorText || 'Validated object is not False'); } return validatedObject; }
[ "function", "booleanFalse", "(", "validatedObject", ",", "errorText", ")", "{", "if", "(", "!", "_", ".", "isBoolean", "(", "validatedObject", ")", "||", "validatedObject", ")", "{", "throw", "new", "ValidationError", "(", "errorText", "||", "'Validated object is not False'", ")", ";", "}", "return", "validatedObject", ";", "}" ]
Checks value to be a False boolean @param {*} validatedObject @param {String} [errorText] - message for error thrown if validation fails @returns {boolean} validatedObject
[ "Checks", "value", "to", "be", "a", "False", "boolean" ]
6cc2a41e9dd6407f29986ed605840d30234802d6
https://github.com/kibertoad/validation-utils/blob/6cc2a41e9dd6407f29986ed605840d30234802d6/lib/validation.helper.js#L200-L205
train
kibertoad/validation-utils
lib/validation.helper.js
withProperties
function withProperties(validatedObject, validatedProperties) { notNil(validatedObject); const undefinedProperties = _.filter(validatedProperties, function(property) { return !validatedObject.hasOwnProperty(property); }); if (!_.isEmpty(undefinedProperties)) { throw new ValidationError("Validated object doesn't have properties: " + undefinedProperties); } return validatedObject; }
javascript
function withProperties(validatedObject, validatedProperties) { notNil(validatedObject); const undefinedProperties = _.filter(validatedProperties, function(property) { return !validatedObject.hasOwnProperty(property); }); if (!_.isEmpty(undefinedProperties)) { throw new ValidationError("Validated object doesn't have properties: " + undefinedProperties); } return validatedObject; }
[ "function", "withProperties", "(", "validatedObject", ",", "validatedProperties", ")", "{", "notNil", "(", "validatedObject", ")", ";", "const", "undefinedProperties", "=", "_", ".", "filter", "(", "validatedProperties", ",", "function", "(", "property", ")", "{", "return", "!", "validatedObject", ".", "hasOwnProperty", "(", "property", ")", ";", "}", ")", ";", "if", "(", "!", "_", ".", "isEmpty", "(", "undefinedProperties", ")", ")", "{", "throw", "new", "ValidationError", "(", "\"Validated object doesn't have properties: \"", "+", "undefinedProperties", ")", ";", "}", "return", "validatedObject", ";", "}" ]
Checks object to have at least a given set of properties defined @param {*} validatedObject @param {String[]} validatedProperties - names of properties which existence should be checked @returns {*} validatedObject
[ "Checks", "object", "to", "have", "at", "least", "a", "given", "set", "of", "properties", "defined" ]
6cc2a41e9dd6407f29986ed605840d30234802d6
https://github.com/kibertoad/validation-utils/blob/6cc2a41e9dd6407f29986ed605840d30234802d6/lib/validation.helper.js#L252-L263
train
kibertoad/validation-utils
lib/validation.helper.js
instanceOf
function instanceOf(validatedObject, expectedClass, errorText) { if (!(validatedObject instanceof expectedClass)) { throw new ValidationError( errorText || `Validated object is not an instance of ${expectedClass.name}` ); } return validatedObject; }
javascript
function instanceOf(validatedObject, expectedClass, errorText) { if (!(validatedObject instanceof expectedClass)) { throw new ValidationError( errorText || `Validated object is not an instance of ${expectedClass.name}` ); } return validatedObject; }
[ "function", "instanceOf", "(", "validatedObject", ",", "expectedClass", ",", "errorText", ")", "{", "if", "(", "!", "(", "validatedObject", "instanceof", "expectedClass", ")", ")", "{", "throw", "new", "ValidationError", "(", "errorText", "||", "`", "${", "expectedClass", ".", "name", "}", "`", ")", ";", "}", "return", "validatedObject", ";", "}" ]
Checks value to be an instance of a given class @param validatedObject @param {class} expectedClass @param {string} [errorText] - message for error thrown if validation fails @returns {Object} validatedObject
[ "Checks", "value", "to", "be", "an", "instance", "of", "a", "given", "class" ]
6cc2a41e9dd6407f29986ed605840d30234802d6
https://github.com/kibertoad/validation-utils/blob/6cc2a41e9dd6407f29986ed605840d30234802d6/lib/validation.helper.js#L298-L305
train
kibertoad/validation-utils
lib/validation.helper.js
inheritsFrom
function inheritsFrom(validatedClass, expectedParentClass, errorText) { if ( //fail-fast if it is nil !validatedClass || //lenient check whether class directly or indirectly inherits from expected class (!(validatedClass.prototype instanceof expectedParentClass) && validatedClass !== expectedParentClass) ) { throw new ValidationError( errorText || `Validated class does not inherit from ${expectedParentClass.name}` ); } return validatedClass; }
javascript
function inheritsFrom(validatedClass, expectedParentClass, errorText) { if ( //fail-fast if it is nil !validatedClass || //lenient check whether class directly or indirectly inherits from expected class (!(validatedClass.prototype instanceof expectedParentClass) && validatedClass !== expectedParentClass) ) { throw new ValidationError( errorText || `Validated class does not inherit from ${expectedParentClass.name}` ); } return validatedClass; }
[ "function", "inheritsFrom", "(", "validatedClass", ",", "expectedParentClass", ",", "errorText", ")", "{", "if", "(", "!", "validatedClass", "||", "(", "!", "(", "validatedClass", ".", "prototype", "instanceof", "expectedParentClass", ")", "&&", "validatedClass", "!==", "expectedParentClass", ")", ")", "{", "throw", "new", "ValidationError", "(", "errorText", "||", "`", "${", "expectedParentClass", ".", "name", "}", "`", ")", ";", "}", "return", "validatedClass", ";", "}" ]
Checks value to inherit from a given class or to be that class @param validatedClass @param {class} expectedParentClass @param {string} [errorText] - message for error thrown if validation fails @returns {Object} validatedObject
[ "Checks", "value", "to", "inherit", "from", "a", "given", "class", "or", "to", "be", "that", "class" ]
6cc2a41e9dd6407f29986ed605840d30234802d6
https://github.com/kibertoad/validation-utils/blob/6cc2a41e9dd6407f29986ed605840d30234802d6/lib/validation.helper.js#L314-L327
train
ryan-self/exec-plan
main.js
function (execPlan, error, stderr, errorHandler) { var shouldContinue = execPlan.continuesOnError(); // default to using configured policy var errorHandlerDefined = utils.isFunction(errorHandler); var errorHandlerReturn; var shouldOverridePolicy; // whether the given error handler is overriding the // "continue on error" policy already set on the exec plan // determine whether the "continue on error" policy should be overridden by the given error // error handler. this is determined by whether the given error handler returns either true // or false. any other return, e.g., undefined, will signify that the policy should be used. if (errorHandlerDefined) errorHandlerReturn = errorHandler(error, stderr); shouldOverridePolicy = ((errorHandlerReturn === true) || (errorHandlerReturn === false)); if (shouldOverridePolicy) { shouldContinue = errorHandlerReturn; } else { // not overriding the policy has the side-effect of allowing 'execerror' to fire execPlan.emit('execerror', error, stderr); } return shouldContinue; }
javascript
function (execPlan, error, stderr, errorHandler) { var shouldContinue = execPlan.continuesOnError(); // default to using configured policy var errorHandlerDefined = utils.isFunction(errorHandler); var errorHandlerReturn; var shouldOverridePolicy; // whether the given error handler is overriding the // "continue on error" policy already set on the exec plan // determine whether the "continue on error" policy should be overridden by the given error // error handler. this is determined by whether the given error handler returns either true // or false. any other return, e.g., undefined, will signify that the policy should be used. if (errorHandlerDefined) errorHandlerReturn = errorHandler(error, stderr); shouldOverridePolicy = ((errorHandlerReturn === true) || (errorHandlerReturn === false)); if (shouldOverridePolicy) { shouldContinue = errorHandlerReturn; } else { // not overriding the policy has the side-effect of allowing 'execerror' to fire execPlan.emit('execerror', error, stderr); } return shouldContinue; }
[ "function", "(", "execPlan", ",", "error", ",", "stderr", ",", "errorHandler", ")", "{", "var", "shouldContinue", "=", "execPlan", ".", "continuesOnError", "(", ")", ";", "var", "errorHandlerDefined", "=", "utils", ".", "isFunction", "(", "errorHandler", ")", ";", "var", "errorHandlerReturn", ";", "var", "shouldOverridePolicy", ";", "if", "(", "errorHandlerDefined", ")", "errorHandlerReturn", "=", "errorHandler", "(", "error", ",", "stderr", ")", ";", "shouldOverridePolicy", "=", "(", "(", "errorHandlerReturn", "===", "true", ")", "||", "(", "errorHandlerReturn", "===", "false", ")", ")", ";", "if", "(", "shouldOverridePolicy", ")", "{", "shouldContinue", "=", "errorHandlerReturn", ";", "}", "else", "{", "execPlan", ".", "emit", "(", "'execerror'", ",", "error", ",", "stderr", ")", ";", "}", "return", "shouldContinue", ";", "}" ]
Provide a common handler for errors that occur during the execution of a plan. @param execPlan ExecPlan @param error Error @param stderr String @param errorHandler Function @param error Error @param stderr String @return Boolean - whether the plan should continue to execute
[ "Provide", "a", "common", "handler", "for", "errors", "that", "occur", "during", "the", "execution", "of", "a", "plan", "." ]
28110ea45aac02fb6a6674ba7783d40db5389b07
https://github.com/ryan-self/exec-plan/blob/28110ea45aac02fb6a6674ba7783d40db5389b07/main.js#L29-L48
train
ryan-self/exec-plan
main.js
function (execPlan, first, preLogic, command, options, errorHandler, nextStep) { return function (error, stdout, stderr) { var shouldContinue; // whether the plan should continue executing beyond this step // log stdout/err if (!first) { // a previous step's stdout/err is available if (execPlan.willAutoPrintOut()) console.log(stdout); if (error && execPlan.willAutoPrintErr()) console.error(stderr); } // continue execution plan, unless it should be stopped, as determined by, e.g., // the error handler. shouldContinue = (!error || handleError(execPlan, error, stderr, errorHandler)); if (shouldContinue) { preLogic(stdout); if (options === null) exec(command, nextStep); else exec(command, options, nextStep); } else { finish(execPlan); } }; }
javascript
function (execPlan, first, preLogic, command, options, errorHandler, nextStep) { return function (error, stdout, stderr) { var shouldContinue; // whether the plan should continue executing beyond this step // log stdout/err if (!first) { // a previous step's stdout/err is available if (execPlan.willAutoPrintOut()) console.log(stdout); if (error && execPlan.willAutoPrintErr()) console.error(stderr); } // continue execution plan, unless it should be stopped, as determined by, e.g., // the error handler. shouldContinue = (!error || handleError(execPlan, error, stderr, errorHandler)); if (shouldContinue) { preLogic(stdout); if (options === null) exec(command, nextStep); else exec(command, options, nextStep); } else { finish(execPlan); } }; }
[ "function", "(", "execPlan", ",", "first", ",", "preLogic", ",", "command", ",", "options", ",", "errorHandler", ",", "nextStep", ")", "{", "return", "function", "(", "error", ",", "stdout", ",", "stderr", ")", "{", "var", "shouldContinue", ";", "if", "(", "!", "first", ")", "{", "if", "(", "execPlan", ".", "willAutoPrintOut", "(", ")", ")", "console", ".", "log", "(", "stdout", ")", ";", "if", "(", "error", "&&", "execPlan", ".", "willAutoPrintErr", "(", ")", ")", "console", ".", "error", "(", "stderr", ")", ";", "}", "shouldContinue", "=", "(", "!", "error", "||", "handleError", "(", "execPlan", ",", "error", ",", "stderr", ",", "errorHandler", ")", ")", ";", "if", "(", "shouldContinue", ")", "{", "preLogic", "(", "stdout", ")", ";", "if", "(", "options", "===", "null", ")", "exec", "(", "command", ",", "nextStep", ")", ";", "else", "exec", "(", "command", ",", "options", ",", "nextStep", ")", ";", "}", "else", "{", "finish", "(", "execPlan", ")", ";", "}", "}", ";", "}" ]
this is an internal API, so for the time being, assume all arguments are valid. provides a function that corresponds to a 'step' in an execution plan. @param execPlan ExecPlan @param first Boolean - whether this corresponds to the 'first' step in execution plan. @param preLogic Function - function to execute before command is exec'd. See: ExecPlan.add. @param command String - the command to exec. See: ExecPlan.add. @param options Object - config options for exec. See: ChildProcess.exec. @param errorHandler Function - error handler from previous step. See: ExecPlan.add. @param nextStep Function - the callback for exec for next step. See: ChildProcess.exec. @return Function - callback to use as a step. See: ChildProcess.exec.
[ "this", "is", "an", "internal", "API", "so", "for", "the", "time", "being", "assume", "all", "arguments", "are", "valid", ".", "provides", "a", "function", "that", "corresponds", "to", "a", "step", "in", "an", "execution", "plan", "." ]
28110ea45aac02fb6a6674ba7783d40db5389b07
https://github.com/ryan-self/exec-plan/blob/28110ea45aac02fb6a6674ba7783d40db5389b07/main.js#L88-L109
train
RetailMeNotSandbox/roux
lib/ingredient.js
Ingredient
function Ingredient(config) { this.name = config.name; this.path = config.path; this.pantryName = config.pantryName; this.entryPoints = _.clone(config.entryPoints); }
javascript
function Ingredient(config) { this.name = config.name; this.path = config.path; this.pantryName = config.pantryName; this.entryPoints = _.clone(config.entryPoints); }
[ "function", "Ingredient", "(", "config", ")", "{", "this", ".", "name", "=", "config", ".", "name", ";", "this", ".", "path", "=", "config", ".", "path", ";", "this", ".", "pantryName", "=", "config", ".", "pantryName", ";", "this", ".", "entryPoints", "=", "_", ".", "clone", "(", "config", ".", "entryPoints", ")", ";", "}" ]
Interface to a Roux ingredient @param {Object} config - Ingredient configuration @param {string} config.path - the path to the ingredient @param {string} config.name - the name of the ingredient @param {string} config.pantryName - the name of the pantry @param {boolean[]} config.entryPoints - the entryPoints the ingredient provides
[ "Interface", "to", "a", "Roux", "ingredient" ]
519616c4deeb47545da44098767e71dfd10a0e83
https://github.com/RetailMeNotSandbox/roux/blob/519616c4deeb47545da44098767e71dfd10a0e83/lib/ingredient.js#L15-L20
train
jhermsmeier/node-udif
lib/footer.js
function( buffer, offset ) { offset = offset || 0 this.signature = buffer.readUInt32BE( offset + 0 ) if( this.signature !== Footer.signature ) { var expected = Footer.signature.toString(16) var actual = this.signature.toString(16) throw new Error( `Invalid footer signature: Expected 0x${expected}, saw 0x${actual}` ) } this.version = buffer.readUInt32BE( offset + 4 ) this.headerSize = buffer.readUInt32BE( offset + 8 ) this.flags = buffer.readUInt32BE( offset + 12 ) this.runningDataForkOffset = uint64.readBE( buffer, offset + 16, 8 ) this.dataForkOffset = uint64.readBE( buffer, offset + 24, 8 ) this.dataForkLength = uint64.readBE( buffer, offset + 32, 8 ) this.resourceForkOffset = uint64.readBE( buffer, offset + 40, 8 ) this.resourceForkLength = uint64.readBE( buffer, offset + 48, 8 ) this.segmentNumber = buffer.readUInt32BE( offset + 56 ) this.segmentCount = buffer.readUInt32BE( offset + 60 ) buffer.copy( this.segmentId, 0, offset + 64, offset + 64 + 16 ) this.dataChecksum.parse( buffer, offset + 80 ) this.xmlOffset = uint64.readBE( buffer, offset + 216, 8 ) this.xmlLength = uint64.readBE( buffer, offset + 224, 8 ) buffer.copy( this.reserved1, 0, offset + 232, offset + 232 + 120 ) this.checksum.parse( buffer, offset + 352 ) this.imageVariant = buffer.readUInt32BE( offset + 488 ) this.sectorCount = uint64.readBE( buffer, offset + 492, 8 ) this.reserved2 = buffer.readUInt32BE( offset + 500 ) this.reserved3 = buffer.readUInt32BE( offset + 504 ) this.reserved4 = buffer.readUInt32BE( offset + 508 ) return this }
javascript
function( buffer, offset ) { offset = offset || 0 this.signature = buffer.readUInt32BE( offset + 0 ) if( this.signature !== Footer.signature ) { var expected = Footer.signature.toString(16) var actual = this.signature.toString(16) throw new Error( `Invalid footer signature: Expected 0x${expected}, saw 0x${actual}` ) } this.version = buffer.readUInt32BE( offset + 4 ) this.headerSize = buffer.readUInt32BE( offset + 8 ) this.flags = buffer.readUInt32BE( offset + 12 ) this.runningDataForkOffset = uint64.readBE( buffer, offset + 16, 8 ) this.dataForkOffset = uint64.readBE( buffer, offset + 24, 8 ) this.dataForkLength = uint64.readBE( buffer, offset + 32, 8 ) this.resourceForkOffset = uint64.readBE( buffer, offset + 40, 8 ) this.resourceForkLength = uint64.readBE( buffer, offset + 48, 8 ) this.segmentNumber = buffer.readUInt32BE( offset + 56 ) this.segmentCount = buffer.readUInt32BE( offset + 60 ) buffer.copy( this.segmentId, 0, offset + 64, offset + 64 + 16 ) this.dataChecksum.parse( buffer, offset + 80 ) this.xmlOffset = uint64.readBE( buffer, offset + 216, 8 ) this.xmlLength = uint64.readBE( buffer, offset + 224, 8 ) buffer.copy( this.reserved1, 0, offset + 232, offset + 232 + 120 ) this.checksum.parse( buffer, offset + 352 ) this.imageVariant = buffer.readUInt32BE( offset + 488 ) this.sectorCount = uint64.readBE( buffer, offset + 492, 8 ) this.reserved2 = buffer.readUInt32BE( offset + 500 ) this.reserved3 = buffer.readUInt32BE( offset + 504 ) this.reserved4 = buffer.readUInt32BE( offset + 508 ) return this }
[ "function", "(", "buffer", ",", "offset", ")", "{", "offset", "=", "offset", "||", "0", "this", ".", "signature", "=", "buffer", ".", "readUInt32BE", "(", "offset", "+", "0", ")", "if", "(", "this", ".", "signature", "!==", "Footer", ".", "signature", ")", "{", "var", "expected", "=", "Footer", ".", "signature", ".", "toString", "(", "16", ")", "var", "actual", "=", "this", ".", "signature", ".", "toString", "(", "16", ")", "throw", "new", "Error", "(", "`", "${", "expected", "}", "${", "actual", "}", "`", ")", "}", "this", ".", "version", "=", "buffer", ".", "readUInt32BE", "(", "offset", "+", "4", ")", "this", ".", "headerSize", "=", "buffer", ".", "readUInt32BE", "(", "offset", "+", "8", ")", "this", ".", "flags", "=", "buffer", ".", "readUInt32BE", "(", "offset", "+", "12", ")", "this", ".", "runningDataForkOffset", "=", "uint64", ".", "readBE", "(", "buffer", ",", "offset", "+", "16", ",", "8", ")", "this", ".", "dataForkOffset", "=", "uint64", ".", "readBE", "(", "buffer", ",", "offset", "+", "24", ",", "8", ")", "this", ".", "dataForkLength", "=", "uint64", ".", "readBE", "(", "buffer", ",", "offset", "+", "32", ",", "8", ")", "this", ".", "resourceForkOffset", "=", "uint64", ".", "readBE", "(", "buffer", ",", "offset", "+", "40", ",", "8", ")", "this", ".", "resourceForkLength", "=", "uint64", ".", "readBE", "(", "buffer", ",", "offset", "+", "48", ",", "8", ")", "this", ".", "segmentNumber", "=", "buffer", ".", "readUInt32BE", "(", "offset", "+", "56", ")", "this", ".", "segmentCount", "=", "buffer", ".", "readUInt32BE", "(", "offset", "+", "60", ")", "buffer", ".", "copy", "(", "this", ".", "segmentId", ",", "0", ",", "offset", "+", "64", ",", "offset", "+", "64", "+", "16", ")", "this", ".", "dataChecksum", ".", "parse", "(", "buffer", ",", "offset", "+", "80", ")", "this", ".", "xmlOffset", "=", "uint64", ".", "readBE", "(", "buffer", ",", "offset", "+", "216", ",", "8", ")", "this", ".", "xmlLength", "=", "uint64", ".", "readBE", "(", "buffer", ",", "offset", "+", "224", ",", "8", ")", "buffer", ".", "copy", "(", "this", ".", "reserved1", ",", "0", ",", "offset", "+", "232", ",", "offset", "+", "232", "+", "120", ")", "this", ".", "checksum", ".", "parse", "(", "buffer", ",", "offset", "+", "352", ")", "this", ".", "imageVariant", "=", "buffer", ".", "readUInt32BE", "(", "offset", "+", "488", ")", "this", ".", "sectorCount", "=", "uint64", ".", "readBE", "(", "buffer", ",", "offset", "+", "492", ",", "8", ")", "this", ".", "reserved2", "=", "buffer", ".", "readUInt32BE", "(", "offset", "+", "500", ")", "this", ".", "reserved3", "=", "buffer", ".", "readUInt32BE", "(", "offset", "+", "504", ")", "this", ".", "reserved4", "=", "buffer", ".", "readUInt32BE", "(", "offset", "+", "508", ")", "return", "this", "}" ]
Parse a Koly block from a buffer @param {Buffer} buffer @param {Number} [offset=0] @returns {Footer}
[ "Parse", "a", "Koly", "block", "from", "a", "buffer" ]
1f5ee84d617e8ebafc8740aec0a734602a1e8b13
https://github.com/jhermsmeier/node-udif/blob/1f5ee84d617e8ebafc8740aec0a734602a1e8b13/lib/footer.js#L86-L129
train
LaunchPadLab/lp-redux-api
src/handlers/handle-success.js
handleSuccess
function handleSuccess (handler) { return (state, action) => isSuccessAction(action) ? handler(state, action, getDataFromAction(action)) : state }
javascript
function handleSuccess (handler) { return (state, action) => isSuccessAction(action) ? handler(state, action, getDataFromAction(action)) : state }
[ "function", "handleSuccess", "(", "handler", ")", "{", "return", "(", "state", ",", "action", ")", "=>", "isSuccessAction", "(", "action", ")", "?", "handler", "(", "state", ",", "action", ",", "getDataFromAction", "(", "action", ")", ")", ":", "state", "}" ]
A function that takes an API action handler and only applies that handler when the request succeeds. @name handleSuccess @param {Function} handler - An action handler that is passed `state`, `action` and `data` params @returns {Function} An action handler that runs when a request is successful @example handleActions({ [apiActions.fetchUser]: handleSuccess((state, action) => { // This code only runs when the call was successful return set('currentUser', action.payload.data, state) }) })
[ "A", "function", "that", "takes", "an", "API", "action", "handler", "and", "only", "applies", "that", "handler", "when", "the", "request", "succeeds", "." ]
73eee231067365326780ddc1dbbfa50d3e65defc
https://github.com/LaunchPadLab/lp-redux-api/blob/73eee231067365326780ddc1dbbfa50d3e65defc/src/handlers/handle-success.js#L20-L22
train
emmetio/stylesheet-formatters
format/css.js
injectFields
function injectFields(string, values) { const fieldsModel = parseFields(string); const fieldsAmount = fieldsModel.fields.length; if (fieldsAmount) { values = values.slice(); if (values.length > fieldsAmount) { // More values that output fields: collapse rest values into // a single token values = values.slice(0, fieldsAmount - 1) .concat(values.slice(fieldsAmount - 1).join(', ')); } while (values.length) { const value = values.shift(); const field = fieldsModel.fields.shift(); const delta = value.length - field.length; fieldsModel.string = fieldsModel.string.slice(0, field.location) + value + fieldsModel.string.slice(field.location + field.length); // Update location of the rest fields in string for (let i = 0, il = fieldsModel.fields.length; i < il; i++) { fieldsModel.fields[i].location += delta; } } } return fieldsModel; }
javascript
function injectFields(string, values) { const fieldsModel = parseFields(string); const fieldsAmount = fieldsModel.fields.length; if (fieldsAmount) { values = values.slice(); if (values.length > fieldsAmount) { // More values that output fields: collapse rest values into // a single token values = values.slice(0, fieldsAmount - 1) .concat(values.slice(fieldsAmount - 1).join(', ')); } while (values.length) { const value = values.shift(); const field = fieldsModel.fields.shift(); const delta = value.length - field.length; fieldsModel.string = fieldsModel.string.slice(0, field.location) + value + fieldsModel.string.slice(field.location + field.length); // Update location of the rest fields in string for (let i = 0, il = fieldsModel.fields.length; i < il; i++) { fieldsModel.fields[i].location += delta; } } } return fieldsModel; }
[ "function", "injectFields", "(", "string", ",", "values", ")", "{", "const", "fieldsModel", "=", "parseFields", "(", "string", ")", ";", "const", "fieldsAmount", "=", "fieldsModel", ".", "fields", ".", "length", ";", "if", "(", "fieldsAmount", ")", "{", "values", "=", "values", ".", "slice", "(", ")", ";", "if", "(", "values", ".", "length", ">", "fieldsAmount", ")", "{", "values", "=", "values", ".", "slice", "(", "0", ",", "fieldsAmount", "-", "1", ")", ".", "concat", "(", "values", ".", "slice", "(", "fieldsAmount", "-", "1", ")", ".", "join", "(", "', '", ")", ")", ";", "}", "while", "(", "values", ".", "length", ")", "{", "const", "value", "=", "values", ".", "shift", "(", ")", ";", "const", "field", "=", "fieldsModel", ".", "fields", ".", "shift", "(", ")", ";", "const", "delta", "=", "value", ".", "length", "-", "field", ".", "length", ";", "fieldsModel", ".", "string", "=", "fieldsModel", ".", "string", ".", "slice", "(", "0", ",", "field", ".", "location", ")", "+", "value", "+", "fieldsModel", ".", "string", ".", "slice", "(", "field", ".", "location", "+", "field", ".", "length", ")", ";", "for", "(", "let", "i", "=", "0", ",", "il", "=", "fieldsModel", ".", "fields", ".", "length", ";", "i", "<", "il", ";", "i", "++", ")", "{", "fieldsModel", ".", "fields", "[", "i", "]", ".", "location", "+=", "delta", ";", "}", "}", "}", "return", "fieldsModel", ";", "}" ]
Injects given field values at each field of given string @param {String} string @param {String[]} attributes @return {FieldString}
[ "Injects", "given", "field", "values", "at", "each", "field", "of", "given", "string" ]
1ba9fa2609b8088e7567547990f123106de84b1d
https://github.com/emmetio/stylesheet-formatters/blob/1ba9fa2609b8088e7567547990f123106de84b1d/format/css.js#L58-L88
train
mikolalysenko/polytope-closest-point
lib/closest_point_0d.js
closestPoint0d
function closestPoint0d(a, x, result) { var d = 0.0; for(var i=0; i<x.length; ++i) { result[i] = a[i]; var t = a[i] - x[i]; d += t * t; } return d; }
javascript
function closestPoint0d(a, x, result) { var d = 0.0; for(var i=0; i<x.length; ++i) { result[i] = a[i]; var t = a[i] - x[i]; d += t * t; } return d; }
[ "function", "closestPoint0d", "(", "a", ",", "x", ",", "result", ")", "{", "var", "d", "=", "0.0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "x", ".", "length", ";", "++", "i", ")", "{", "result", "[", "i", "]", "=", "a", "[", "i", "]", ";", "var", "t", "=", "a", "[", "i", "]", "-", "x", "[", "i", "]", ";", "d", "+=", "t", "*", "t", ";", "}", "return", "d", ";", "}" ]
Closest point to a point is trivial
[ "Closest", "point", "to", "a", "point", "is", "trivial" ]
de523419bf633743f4333d0768b5e929bc82fd80
https://github.com/mikolalysenko/polytope-closest-point/blob/de523419bf633743f4333d0768b5e929bc82fd80/lib/closest_point_0d.js#L4-L12
train
zaim/immpatch
lib/patch.js
patch
function patch(object, ops) { ops = Array.isArray(ops) ? ops : [ops]; object = ops.reduce(function (ob, op) { op = (0, _parse2['default'])(op, ob); return operators[op.op].call(ob, op); }, object); // Re-convert the returned object into an // immutable structure, in case the entire // object was replaced with a POJO return _immutable2['default'].fromJS(object); }
javascript
function patch(object, ops) { ops = Array.isArray(ops) ? ops : [ops]; object = ops.reduce(function (ob, op) { op = (0, _parse2['default'])(op, ob); return operators[op.op].call(ob, op); }, object); // Re-convert the returned object into an // immutable structure, in case the entire // object was replaced with a POJO return _immutable2['default'].fromJS(object); }
[ "function", "patch", "(", "object", ",", "ops", ")", "{", "ops", "=", "Array", ".", "isArray", "(", "ops", ")", "?", "ops", ":", "[", "ops", "]", ";", "object", "=", "ops", ".", "reduce", "(", "function", "(", "ob", ",", "op", ")", "{", "op", "=", "(", "0", ",", "_parse2", "[", "'default'", "]", ")", "(", "op", ",", "ob", ")", ";", "return", "operators", "[", "op", ".", "op", "]", ".", "call", "(", "ob", ",", "op", ")", ";", "}", ",", "object", ")", ";", "return", "_immutable2", "[", "'default'", "]", ".", "fromJS", "(", "object", ")", ";", "}" ]
Update the immutable object using JSON Patch operations. @param {object} object @param {array|object} ops @returns {object}
[ "Update", "the", "immutable", "object", "using", "JSON", "Patch", "operations", "." ]
039647d10506bc928f95c962f7cd5950574637e8
https://github.com/zaim/immpatch/blob/039647d10506bc928f95c962f7cd5950574637e8/lib/patch.js#L171-L181
train
JakeSidSmith/slik
src/index.js
invert
function invert () { if (Immutable.Iterable.isIterable(toValues)) { toValues = toValues.map(mapInvertValues); } else { toValues = mapInvertValues(toValues); } return self; }
javascript
function invert () { if (Immutable.Iterable.isIterable(toValues)) { toValues = toValues.map(mapInvertValues); } else { toValues = mapInvertValues(toValues); } return self; }
[ "function", "invert", "(", ")", "{", "if", "(", "Immutable", ".", "Iterable", ".", "isIterable", "(", "toValues", ")", ")", "{", "toValues", "=", "toValues", ".", "map", "(", "mapInvertValues", ")", ";", "}", "else", "{", "toValues", "=", "mapInvertValues", "(", "toValues", ")", ";", "}", "return", "self", ";", "}" ]
Invert animation values
[ "Invert", "animation", "values" ]
493e7759fa608befc96d42e2beb4a7f05bea0ee4
https://github.com/JakeSidSmith/slik/blob/493e7759fa608befc96d42e2beb4a7f05bea0ee4/src/index.js#L301-L309
train
JakeSidSmith/slik
src/index.js
start
function start () { var now = performance.now(); if (typeof pausedAfter !== 'undefined') { startTime = now + pausedAfter; } else { startTime = now + delayMillis; } lastTime = startTime; pausedAfter = undefined; triggerEvent('start'); startLoop(animationId, animationLoop); return self; }
javascript
function start () { var now = performance.now(); if (typeof pausedAfter !== 'undefined') { startTime = now + pausedAfter; } else { startTime = now + delayMillis; } lastTime = startTime; pausedAfter = undefined; triggerEvent('start'); startLoop(animationId, animationLoop); return self; }
[ "function", "start", "(", ")", "{", "var", "now", "=", "performance", ".", "now", "(", ")", ";", "if", "(", "typeof", "pausedAfter", "!==", "'undefined'", ")", "{", "startTime", "=", "now", "+", "pausedAfter", ";", "}", "else", "{", "startTime", "=", "now", "+", "delayMillis", ";", "}", "lastTime", "=", "startTime", ";", "pausedAfter", "=", "undefined", ";", "triggerEvent", "(", "'start'", ")", ";", "startLoop", "(", "animationId", ",", "animationLoop", ")", ";", "return", "self", ";", "}" ]
Start or resume animation
[ "Start", "or", "resume", "animation" ]
493e7759fa608befc96d42e2beb4a7f05bea0ee4
https://github.com/JakeSidSmith/slik/blob/493e7759fa608befc96d42e2beb4a7f05bea0ee4/src/index.js#L320-L337
train
JakeSidSmith/slik
src/index.js
stop
function stop () { currentValues = fromValues; triggerEvent('stop'); stopLoop(animationId); pausedAfter = undefined; startTime = undefined; return self; }
javascript
function stop () { currentValues = fromValues; triggerEvent('stop'); stopLoop(animationId); pausedAfter = undefined; startTime = undefined; return self; }
[ "function", "stop", "(", ")", "{", "currentValues", "=", "fromValues", ";", "triggerEvent", "(", "'stop'", ")", ";", "stopLoop", "(", "animationId", ")", ";", "pausedAfter", "=", "undefined", ";", "startTime", "=", "undefined", ";", "return", "self", ";", "}" ]
Stop animation and resume from beginning
[ "Stop", "animation", "and", "resume", "from", "beginning" ]
493e7759fa608befc96d42e2beb4a7f05bea0ee4
https://github.com/JakeSidSmith/slik/blob/493e7759fa608befc96d42e2beb4a7f05bea0ee4/src/index.js#L340-L347
train
JakeSidSmith/slik
src/index.js
pause
function pause () { triggerEvent('pause'); stopLoop(animationId); pausedAfter = startTime - performance.now(); startTime = undefined; return self; }
javascript
function pause () { triggerEvent('pause'); stopLoop(animationId); pausedAfter = startTime - performance.now(); startTime = undefined; return self; }
[ "function", "pause", "(", ")", "{", "triggerEvent", "(", "'pause'", ")", ";", "stopLoop", "(", "animationId", ")", ";", "pausedAfter", "=", "startTime", "-", "performance", ".", "now", "(", ")", ";", "startTime", "=", "undefined", ";", "return", "self", ";", "}" ]
Pause animation and resume from this point
[ "Pause", "animation", "and", "resume", "from", "this", "point" ]
493e7759fa608befc96d42e2beb4a7f05bea0ee4
https://github.com/JakeSidSmith/slik/blob/493e7759fa608befc96d42e2beb4a7f05bea0ee4/src/index.js#L350-L356
train
JakeSidSmith/slik
src/index.js
first
function first (callback) { if (typeof callback !== 'function') { throw new Error('Callback must be a function, instead got: ' + (typeof callback)); } function firstCallback (result) { callback(result); unbind('start', firstCallback); } bind('start', firstCallback); bind('stop', unbind.bind(null, 'end', firstCallback)); return self; }
javascript
function first (callback) { if (typeof callback !== 'function') { throw new Error('Callback must be a function, instead got: ' + (typeof callback)); } function firstCallback (result) { callback(result); unbind('start', firstCallback); } bind('start', firstCallback); bind('stop', unbind.bind(null, 'end', firstCallback)); return self; }
[ "function", "first", "(", "callback", ")", "{", "if", "(", "typeof", "callback", "!==", "'function'", ")", "{", "throw", "new", "Error", "(", "'Callback must be a function, instead got: '", "+", "(", "typeof", "callback", ")", ")", ";", "}", "function", "firstCallback", "(", "result", ")", "{", "callback", "(", "result", ")", ";", "unbind", "(", "'start'", ",", "firstCallback", ")", ";", "}", "bind", "(", "'start'", ",", "firstCallback", ")", ";", "bind", "(", "'stop'", ",", "unbind", ".", "bind", "(", "null", ",", "'end'", ",", "firstCallback", ")", ")", ";", "return", "self", ";", "}" ]
Run on start and automatically unbind
[ "Run", "on", "start", "and", "automatically", "unbind" ]
493e7759fa608befc96d42e2beb4a7f05bea0ee4
https://github.com/JakeSidSmith/slik/blob/493e7759fa608befc96d42e2beb4a7f05bea0ee4/src/index.js#L407-L421
train
JakeSidSmith/slik
src/index.js
then
function then (callback) { if (typeof callback !== 'function') { throw new Error('Callback must be a function, instead got: ' + (typeof callback)); } function thenCallback (result) { callback(result); unbind('end', thenCallback); } bind('end', thenCallback); bind('stop', unbind.bind(null, 'end', thenCallback)); return self; }
javascript
function then (callback) { if (typeof callback !== 'function') { throw new Error('Callback must be a function, instead got: ' + (typeof callback)); } function thenCallback (result) { callback(result); unbind('end', thenCallback); } bind('end', thenCallback); bind('stop', unbind.bind(null, 'end', thenCallback)); return self; }
[ "function", "then", "(", "callback", ")", "{", "if", "(", "typeof", "callback", "!==", "'function'", ")", "{", "throw", "new", "Error", "(", "'Callback must be a function, instead got: '", "+", "(", "typeof", "callback", ")", ")", ";", "}", "function", "thenCallback", "(", "result", ")", "{", "callback", "(", "result", ")", ";", "unbind", "(", "'end'", ",", "thenCallback", ")", ";", "}", "bind", "(", "'end'", ",", "thenCallback", ")", ";", "bind", "(", "'stop'", ",", "unbind", ".", "bind", "(", "null", ",", "'end'", ",", "thenCallback", ")", ")", ";", "return", "self", ";", "}" ]
Run on complete and automatically unbind
[ "Run", "on", "complete", "and", "automatically", "unbind" ]
493e7759fa608befc96d42e2beb4a7f05bea0ee4
https://github.com/JakeSidSmith/slik/blob/493e7759fa608befc96d42e2beb4a7f05bea0ee4/src/index.js#L424-L438
train
openbiz/openbiz
lib/objects/Application.js
function(routePrefix) { if(routePrefix==='/')routePrefix=''; this.appUrl = routePrefix; var pattern = /^(.*?)\s(.*?)$/ for(var routePath in this.routes) { var routePathArray = routePath.match(pattern); this.openbiz.context[routePathArray[1]](routePrefix+routePathArray[2],this.routes[routePath]); } return this; }
javascript
function(routePrefix) { if(routePrefix==='/')routePrefix=''; this.appUrl = routePrefix; var pattern = /^(.*?)\s(.*?)$/ for(var routePath in this.routes) { var routePathArray = routePath.match(pattern); this.openbiz.context[routePathArray[1]](routePrefix+routePathArray[2],this.routes[routePath]); } return this; }
[ "function", "(", "routePrefix", ")", "{", "if", "(", "routePrefix", "===", "'/'", ")", "routePrefix", "=", "''", ";", "this", ".", "appUrl", "=", "routePrefix", ";", "var", "pattern", "=", "/", "^(.*?)\\s(.*?)$", "/", "for", "(", "var", "routePath", "in", "this", ".", "routes", ")", "{", "var", "routePathArray", "=", "routePath", ".", "match", "(", "pattern", ")", ";", "this", ".", "openbiz", ".", "context", "[", "routePathArray", "[", "1", "]", "]", "(", "routePrefix", "+", "routePathArray", "[", "2", "]", ",", "this", ".", "routes", "[", "routePath", "]", ")", ";", "}", "return", "this", ";", "}" ]
Mounts current application to specified URL router @memberof openbiz.objects.Application @instance @param {string} routePrefix - The prefix of URL to mount this application instance @returns {openbiz.objects.Application} @example // init cubi app to routes => /app/* openbiz.apps['cubi'].initRoutes('/api');
[ "Mounts", "current", "application", "to", "specified", "URL", "router" ]
997f1398396683d7ad667b1b360ce74c7c7fcf6f
https://github.com/openbiz/openbiz/blob/997f1398396683d7ad667b1b360ce74c7c7fcf6f/lib/objects/Application.js#L148-L159
train
axke/rs-api
lib/apis/news.js
News
function News(config) { this.getRecent = function() { return new Promise(function(resolve, reject) { request.rss(config.urls.rss).then(function(data) { resolve(data); }).catch(reject); }); } }
javascript
function News(config) { this.getRecent = function() { return new Promise(function(resolve, reject) { request.rss(config.urls.rss).then(function(data) { resolve(data); }).catch(reject); }); } }
[ "function", "News", "(", "config", ")", "{", "this", ".", "getRecent", "=", "function", "(", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "request", ".", "rss", "(", "config", ".", "urls", ".", "rss", ")", ".", "then", "(", "function", "(", "data", ")", "{", "resolve", "(", "data", ")", ";", "}", ")", ".", "catch", "(", "reject", ")", ";", "}", ")", ";", "}", "}" ]
Module containing to retrieve RS News @module News
[ "Module", "containing", "to", "retrieve", "RS", "News" ]
71af4973e1d079f09b7d888b6d24735784185942
https://github.com/axke/rs-api/blob/71af4973e1d079f09b7d888b6d24735784185942/lib/apis/news.js#L10-L18
train
sguha-work/csv-array
csv-array.js
function(line) { var dataArray = []; var tempString=""; var lineLength = line.length; var index=0; while(index<lineLength) { if(line[index]=='"') { var index2 = index+1; while(line[index2]!='"') { tempString+=line[index2]; index2++; } dataArray.push(tempString); tempString = ""; index = index2+2; continue; } if(line[index]!=",") { tempString += line[index]; index++; continue; } if(line[index]==",") { dataArray.push(tempString); tempString = ""; index++;continue; } } dataArray.push(tempString); return dataArray; }
javascript
function(line) { var dataArray = []; var tempString=""; var lineLength = line.length; var index=0; while(index<lineLength) { if(line[index]=='"') { var index2 = index+1; while(line[index2]!='"') { tempString+=line[index2]; index2++; } dataArray.push(tempString); tempString = ""; index = index2+2; continue; } if(line[index]!=",") { tempString += line[index]; index++; continue; } if(line[index]==",") { dataArray.push(tempString); tempString = ""; index++;continue; } } dataArray.push(tempString); return dataArray; }
[ "function", "(", "line", ")", "{", "var", "dataArray", "=", "[", "]", ";", "var", "tempString", "=", "\"\"", ";", "var", "lineLength", "=", "line", ".", "length", ";", "var", "index", "=", "0", ";", "while", "(", "index", "<", "lineLength", ")", "{", "if", "(", "line", "[", "index", "]", "==", "'\"'", ")", "{", "var", "index2", "=", "index", "+", "1", ";", "while", "(", "line", "[", "index2", "]", "!=", "'\"'", ")", "{", "tempString", "+=", "line", "[", "index2", "]", ";", "index2", "++", ";", "}", "dataArray", ".", "push", "(", "tempString", ")", ";", "tempString", "=", "\"\"", ";", "index", "=", "index2", "+", "2", ";", "continue", ";", "}", "if", "(", "line", "[", "index", "]", "!=", "\",\"", ")", "{", "tempString", "+=", "line", "[", "index", "]", ";", "index", "++", ";", "continue", ";", "}", "if", "(", "line", "[", "index", "]", "==", "\",\"", ")", "{", "dataArray", ".", "push", "(", "tempString", ")", ";", "tempString", "=", "\"\"", ";", "index", "++", ";", "continue", ";", "}", "}", "dataArray", ".", "push", "(", "tempString", ")", ";", "return", "dataArray", ";", "}" ]
returns data from a single line
[ "returns", "data", "from", "a", "single", "line" ]
ce5caaf831c53d2a6341229c553bdf77d6880a5a
https://github.com/sguha-work/csv-array/blob/ce5caaf831c53d2a6341229c553bdf77d6880a5a/csv-array.js#L19-L49
train
madoublet/hashedit
dist/hashedit.js
function() { var x, els; // setup [contentEditable=true] els = document.querySelectorAll( 'p[hashedit-element], [hashedit] h1[hashedit-element], [hashedit] h2[hashedit-element], h3[hashedit-element], h4[hashedit-element], h5[hashedit-element], span[hashedit-element], ul[hashedit-element] li, ol[hashedit-element] li, table[hashedit-element] td, table[hashedit-element] th, blockquote[hashedit-element], pre[hashedit-element]' ); for (x = 0; x < els.length; x += 1) { // add attribute els[x].setAttribute('contentEditable', 'true'); } }
javascript
function() { var x, els; // setup [contentEditable=true] els = document.querySelectorAll( 'p[hashedit-element], [hashedit] h1[hashedit-element], [hashedit] h2[hashedit-element], h3[hashedit-element], h4[hashedit-element], h5[hashedit-element], span[hashedit-element], ul[hashedit-element] li, ol[hashedit-element] li, table[hashedit-element] td, table[hashedit-element] th, blockquote[hashedit-element], pre[hashedit-element]' ); for (x = 0; x < els.length; x += 1) { // add attribute els[x].setAttribute('contentEditable', 'true'); } }
[ "function", "(", ")", "{", "var", "x", ",", "els", ";", "els", "=", "document", ".", "querySelectorAll", "(", "'p[hashedit-element], [hashedit] h1[hashedit-element], [hashedit] h2[hashedit-element], h3[hashedit-element], h4[hashedit-element], h5[hashedit-element], span[hashedit-element], ul[hashedit-element] li, ol[hashedit-element] li, table[hashedit-element] td, table[hashedit-element] th, blockquote[hashedit-element], pre[hashedit-element]'", ")", ";", "for", "(", "x", "=", "0", ";", "x", "<", "els", ".", "length", ";", "x", "+=", "1", ")", "{", "els", "[", "x", "]", ".", "setAttribute", "(", "'contentEditable'", ",", "'true'", ")", ";", "}", "}" ]
Setup content editable element
[ "Setup", "content", "editable", "element" ]
14b5570cc7a97f8bdcfa596ce27260d25f8e18da
https://github.com/madoublet/hashedit/blob/14b5570cc7a97f8bdcfa596ce27260d25f8e18da/dist/hashedit.js#L125-L141
train
madoublet/hashedit
dist/hashedit.js
function() { var x, sortable, els; els = document.querySelectorAll('[hashedit-sortable]'); // walk through sortable clases for (x = 0; x < els.length; x += 1) { if(els[x].firstElementChild === null){ els[x].setAttribute('hashedit-empty', 'true'); } else { els[x].removeAttribute('hashedit-empty'); } } }
javascript
function() { var x, sortable, els; els = document.querySelectorAll('[hashedit-sortable]'); // walk through sortable clases for (x = 0; x < els.length; x += 1) { if(els[x].firstElementChild === null){ els[x].setAttribute('hashedit-empty', 'true'); } else { els[x].removeAttribute('hashedit-empty'); } } }
[ "function", "(", ")", "{", "var", "x", ",", "sortable", ",", "els", ";", "els", "=", "document", ".", "querySelectorAll", "(", "'[hashedit-sortable]'", ")", ";", "for", "(", "x", "=", "0", ";", "x", "<", "els", ".", "length", ";", "x", "+=", "1", ")", "{", "if", "(", "els", "[", "x", "]", ".", "firstElementChild", "===", "null", ")", "{", "els", "[", "x", "]", ".", "setAttribute", "(", "'hashedit-empty'", ",", "'true'", ")", ";", "}", "else", "{", "els", "[", "x", "]", ".", "removeAttribute", "(", "'hashedit-empty'", ")", ";", "}", "}", "}" ]
Sets up empty @param {Array} sortable
[ "Sets", "up", "empty" ]
14b5570cc7a97f8bdcfa596ce27260d25f8e18da
https://github.com/madoublet/hashedit/blob/14b5570cc7a97f8bdcfa596ce27260d25f8e18da/dist/hashedit.js#L147-L165
train
madoublet/hashedit
dist/hashedit.js
function() { var x, els, y, div, blocks, el, next, previous, span; blocks = hashedit.config.blocks; // setup sortable classes els = document.querySelectorAll('[hashedit] ' + blocks); // set [data-hashedit-sortable=true] for (y = 0; y < els.length; y += 1) { // setup blocks if(els[y].querySelector('.hashedit-block-menu') === null) { els[y].setAttribute('hashedit-block', ''); // create element menu div = document.createElement('DIV'); div.setAttribute('class', 'hashedit-block-menu'); div.setAttribute('contentEditable', 'false'); div.innerHTML = '<label><i class="material-icons">more_vert</i> ' + hashedit.i18n('Layout Menu') + '</label>'; // create up span = document.createElement('span'); span.setAttribute('class', 'hashedit-block-add'); span.innerHTML = '<i class="material-icons">add</i> ' + hashedit.i18n('Add'); // append the handle to the wrapper div.appendChild(span); // create up span = document.createElement('span'); span.setAttribute('class', 'hashedit-block-up'); span.innerHTML = '<i class="material-icons">arrow_upward</i> ' + hashedit.i18n('Move Up'); // append the handle to the wrapper div.appendChild(span); // create down span = document.createElement('span'); span.setAttribute('class', 'hashedit-block-down'); span.innerHTML = '<i class="material-icons">arrow_downward</i> ' + hashedit.i18n('Move Down'); // append the handle to the wrapper div.appendChild(span); // create remove span = document.createElement('span'); span.setAttribute('class', 'hashedit-block-duplicate'); span.innerHTML = '<i class="material-icons">content_copy</i> ' + hashedit.i18n('Duplicate'); // append the handle to the wrapper div.appendChild(span); // create properties span = document.createElement('span'); span.setAttribute('class', 'hashedit-block-properties'); span.innerHTML = '<i class="material-icons">settings</i> ' + hashedit.i18n('Settings'); // append the handle to the wrapper div.appendChild(span); // create remove span = document.createElement('span'); span.setAttribute('class', 'hashedit-block-remove'); span.innerHTML = '<i class="material-icons">cancel</i> ' + hashedit.i18n('Remove'); // append the handle to the wrapper div.appendChild(span); els[y].appendChild(div); } } }
javascript
function() { var x, els, y, div, blocks, el, next, previous, span; blocks = hashedit.config.blocks; // setup sortable classes els = document.querySelectorAll('[hashedit] ' + blocks); // set [data-hashedit-sortable=true] for (y = 0; y < els.length; y += 1) { // setup blocks if(els[y].querySelector('.hashedit-block-menu') === null) { els[y].setAttribute('hashedit-block', ''); // create element menu div = document.createElement('DIV'); div.setAttribute('class', 'hashedit-block-menu'); div.setAttribute('contentEditable', 'false'); div.innerHTML = '<label><i class="material-icons">more_vert</i> ' + hashedit.i18n('Layout Menu') + '</label>'; // create up span = document.createElement('span'); span.setAttribute('class', 'hashedit-block-add'); span.innerHTML = '<i class="material-icons">add</i> ' + hashedit.i18n('Add'); // append the handle to the wrapper div.appendChild(span); // create up span = document.createElement('span'); span.setAttribute('class', 'hashedit-block-up'); span.innerHTML = '<i class="material-icons">arrow_upward</i> ' + hashedit.i18n('Move Up'); // append the handle to the wrapper div.appendChild(span); // create down span = document.createElement('span'); span.setAttribute('class', 'hashedit-block-down'); span.innerHTML = '<i class="material-icons">arrow_downward</i> ' + hashedit.i18n('Move Down'); // append the handle to the wrapper div.appendChild(span); // create remove span = document.createElement('span'); span.setAttribute('class', 'hashedit-block-duplicate'); span.innerHTML = '<i class="material-icons">content_copy</i> ' + hashedit.i18n('Duplicate'); // append the handle to the wrapper div.appendChild(span); // create properties span = document.createElement('span'); span.setAttribute('class', 'hashedit-block-properties'); span.innerHTML = '<i class="material-icons">settings</i> ' + hashedit.i18n('Settings'); // append the handle to the wrapper div.appendChild(span); // create remove span = document.createElement('span'); span.setAttribute('class', 'hashedit-block-remove'); span.innerHTML = '<i class="material-icons">cancel</i> ' + hashedit.i18n('Remove'); // append the handle to the wrapper div.appendChild(span); els[y].appendChild(div); } } }
[ "function", "(", ")", "{", "var", "x", ",", "els", ",", "y", ",", "div", ",", "blocks", ",", "el", ",", "next", ",", "previous", ",", "span", ";", "blocks", "=", "hashedit", ".", "config", ".", "blocks", ";", "els", "=", "document", ".", "querySelectorAll", "(", "'[hashedit] '", "+", "blocks", ")", ";", "for", "(", "y", "=", "0", ";", "y", "<", "els", ".", "length", ";", "y", "+=", "1", ")", "{", "if", "(", "els", "[", "y", "]", ".", "querySelector", "(", "'.hashedit-block-menu'", ")", "===", "null", ")", "{", "els", "[", "y", "]", ".", "setAttribute", "(", "'hashedit-block'", ",", "''", ")", ";", "div", "=", "document", ".", "createElement", "(", "'DIV'", ")", ";", "div", ".", "setAttribute", "(", "'class'", ",", "'hashedit-block-menu'", ")", ";", "div", ".", "setAttribute", "(", "'contentEditable'", ",", "'false'", ")", ";", "div", ".", "innerHTML", "=", "'<label><i class=\"material-icons\">more_vert</i> '", "+", "hashedit", ".", "i18n", "(", "'Layout Menu'", ")", "+", "'</label>'", ";", "span", "=", "document", ".", "createElement", "(", "'span'", ")", ";", "span", ".", "setAttribute", "(", "'class'", ",", "'hashedit-block-add'", ")", ";", "span", ".", "innerHTML", "=", "'<i class=\"material-icons\">add</i> '", "+", "hashedit", ".", "i18n", "(", "'Add'", ")", ";", "div", ".", "appendChild", "(", "span", ")", ";", "span", "=", "document", ".", "createElement", "(", "'span'", ")", ";", "span", ".", "setAttribute", "(", "'class'", ",", "'hashedit-block-up'", ")", ";", "span", ".", "innerHTML", "=", "'<i class=\"material-icons\">arrow_upward</i> '", "+", "hashedit", ".", "i18n", "(", "'Move Up'", ")", ";", "div", ".", "appendChild", "(", "span", ")", ";", "span", "=", "document", ".", "createElement", "(", "'span'", ")", ";", "span", ".", "setAttribute", "(", "'class'", ",", "'hashedit-block-down'", ")", ";", "span", ".", "innerHTML", "=", "'<i class=\"material-icons\">arrow_downward</i> '", "+", "hashedit", ".", "i18n", "(", "'Move Down'", ")", ";", "div", ".", "appendChild", "(", "span", ")", ";", "span", "=", "document", ".", "createElement", "(", "'span'", ")", ";", "span", ".", "setAttribute", "(", "'class'", ",", "'hashedit-block-duplicate'", ")", ";", "span", ".", "innerHTML", "=", "'<i class=\"material-icons\">content_copy</i> '", "+", "hashedit", ".", "i18n", "(", "'Duplicate'", ")", ";", "div", ".", "appendChild", "(", "span", ")", ";", "span", "=", "document", ".", "createElement", "(", "'span'", ")", ";", "span", ".", "setAttribute", "(", "'class'", ",", "'hashedit-block-properties'", ")", ";", "span", ".", "innerHTML", "=", "'<i class=\"material-icons\">settings</i> '", "+", "hashedit", ".", "i18n", "(", "'Settings'", ")", ";", "div", ".", "appendChild", "(", "span", ")", ";", "span", "=", "document", ".", "createElement", "(", "'span'", ")", ";", "span", ".", "setAttribute", "(", "'class'", ",", "'hashedit-block-remove'", ")", ";", "span", ".", "innerHTML", "=", "'<i class=\"material-icons\">cancel</i> '", "+", "hashedit", ".", "i18n", "(", "'Remove'", ")", ";", "div", ".", "appendChild", "(", "span", ")", ";", "els", "[", "y", "]", ".", "appendChild", "(", "div", ")", ";", "}", "}", "}" ]
Sets up block @param {Array} sortable
[ "Sets", "up", "block" ]
14b5570cc7a97f8bdcfa596ce27260d25f8e18da
https://github.com/madoublet/hashedit/blob/14b5570cc7a97f8bdcfa596ce27260d25f8e18da/dist/hashedit.js#L171-L249
train
madoublet/hashedit
dist/hashedit.js
function(el) { var menu, span; // set element el.setAttribute('hashedit-element', ''); // create element menu menu = document.createElement('span'); menu.setAttribute('class', 'hashedit-element-menu'); menu.setAttribute('contentEditable', 'false'); menu.innerHTML = '<label><i class="material-icons">more_vert</i> ' + hashedit.i18n('Content Menu') + '</label>'; // create a handle span = document.createElement('span'); span.setAttribute('class', 'hashedit-move'); span.innerHTML = '<i class="material-icons">apps</i> ' + hashedit.i18n('Move'); // append the handle to the wrapper menu.appendChild(span); span = document.createElement('span'); span.setAttribute('class', 'hashedit-properties'); span.innerHTML = '<i class="material-icons">settings</i> ' + hashedit.i18n('Settings'); // append the handle to the wrapper menu.appendChild(span); span = document.createElement('span'); span.setAttribute('class', 'hashedit-remove'); span.innerHTML = '<i class="material-icons">cancel</i> ' + hashedit.i18n('Remove'); // append the handle to the wrapper menu.appendChild(span); // append the handle to the wrapper el.appendChild(menu); }
javascript
function(el) { var menu, span; // set element el.setAttribute('hashedit-element', ''); // create element menu menu = document.createElement('span'); menu.setAttribute('class', 'hashedit-element-menu'); menu.setAttribute('contentEditable', 'false'); menu.innerHTML = '<label><i class="material-icons">more_vert</i> ' + hashedit.i18n('Content Menu') + '</label>'; // create a handle span = document.createElement('span'); span.setAttribute('class', 'hashedit-move'); span.innerHTML = '<i class="material-icons">apps</i> ' + hashedit.i18n('Move'); // append the handle to the wrapper menu.appendChild(span); span = document.createElement('span'); span.setAttribute('class', 'hashedit-properties'); span.innerHTML = '<i class="material-icons">settings</i> ' + hashedit.i18n('Settings'); // append the handle to the wrapper menu.appendChild(span); span = document.createElement('span'); span.setAttribute('class', 'hashedit-remove'); span.innerHTML = '<i class="material-icons">cancel</i> ' + hashedit.i18n('Remove'); // append the handle to the wrapper menu.appendChild(span); // append the handle to the wrapper el.appendChild(menu); }
[ "function", "(", "el", ")", "{", "var", "menu", ",", "span", ";", "el", ".", "setAttribute", "(", "'hashedit-element'", ",", "''", ")", ";", "menu", "=", "document", ".", "createElement", "(", "'span'", ")", ";", "menu", ".", "setAttribute", "(", "'class'", ",", "'hashedit-element-menu'", ")", ";", "menu", ".", "setAttribute", "(", "'contentEditable'", ",", "'false'", ")", ";", "menu", ".", "innerHTML", "=", "'<label><i class=\"material-icons\">more_vert</i> '", "+", "hashedit", ".", "i18n", "(", "'Content Menu'", ")", "+", "'</label>'", ";", "span", "=", "document", ".", "createElement", "(", "'span'", ")", ";", "span", ".", "setAttribute", "(", "'class'", ",", "'hashedit-move'", ")", ";", "span", ".", "innerHTML", "=", "'<i class=\"material-icons\">apps</i> '", "+", "hashedit", ".", "i18n", "(", "'Move'", ")", ";", "menu", ".", "appendChild", "(", "span", ")", ";", "span", "=", "document", ".", "createElement", "(", "'span'", ")", ";", "span", ".", "setAttribute", "(", "'class'", ",", "'hashedit-properties'", ")", ";", "span", ".", "innerHTML", "=", "'<i class=\"material-icons\">settings</i> '", "+", "hashedit", ".", "i18n", "(", "'Settings'", ")", ";", "menu", ".", "appendChild", "(", "span", ")", ";", "span", "=", "document", ".", "createElement", "(", "'span'", ")", ";", "span", ".", "setAttribute", "(", "'class'", ",", "'hashedit-remove'", ")", ";", "span", ".", "innerHTML", "=", "'<i class=\"material-icons\">cancel</i> '", "+", "hashedit", ".", "i18n", "(", "'Remove'", ")", ";", "menu", ".", "appendChild", "(", "span", ")", ";", "el", ".", "appendChild", "(", "menu", ")", ";", "}" ]
Adds an element menu to a given element @param {DOMElement} el
[ "Adds", "an", "element", "menu", "to", "a", "given", "element" ]
14b5570cc7a97f8bdcfa596ce27260d25f8e18da
https://github.com/madoublet/hashedit/blob/14b5570cc7a97f8bdcfa596ce27260d25f8e18da/dist/hashedit.js#L255-L293
train
madoublet/hashedit
dist/hashedit.js
function() { var x, y, els, div, span, el, item, obj, menu, sortable, a; sortable = hashedit.config.sortable; // walk through sortable clases for (x = 0; x < sortable.length; x += 1) { // setup sortable classes els = document.querySelectorAll('[hashedit] ' + sortable[x]); // set [data-hashedit-sortable=true] for (y = 0; y < els.length; y += 1) { // add attribute els[y].setAttribute('hashedit-sortable', ''); } } // wrap elements in the sortable class els = document.querySelectorAll('[hashedit-sortable] > *'); // wrap editable items for (y = 0; y < els.length; y += 1) { hashedit.setupElementMenu(els[y]); } // get all sortable elements els = document.querySelectorAll('[hashedit] [hashedit-sortable]'); // walk through elements for (x = 0; x < els.length; x += 1) { el = els[x]; obj = new Sortable(el, { group: "hashedit-sortable", // or { name: "...", pull: [true, false, clone], put: [true, false, array] } sort: true, // sorting inside list delay: 0, // time in milliseconds to define when the sorting should start disabled: false, // Disables the sortable if set to true. store: null, // @see Store animation: 150, // ms, animation speed moving items when sorting, `0` — without animation handle: ".hashedit-move", // Drag handle selector within list items ghostClass: "hashedit-highlight", // Class name for the drop placeholder scroll: true, // or HTMLElement scrollSensitivity: 30, // px, how near the mouse must be to an edge to start scrolling. scrollSpeed: 10, // px // dragging ended onEnd: function(evt) { // get item item = evt.item; // handle empty hashedit.setupEmpty(); } }); } // set the display of empty columns hashedit.setupEmpty(); }
javascript
function() { var x, y, els, div, span, el, item, obj, menu, sortable, a; sortable = hashedit.config.sortable; // walk through sortable clases for (x = 0; x < sortable.length; x += 1) { // setup sortable classes els = document.querySelectorAll('[hashedit] ' + sortable[x]); // set [data-hashedit-sortable=true] for (y = 0; y < els.length; y += 1) { // add attribute els[y].setAttribute('hashedit-sortable', ''); } } // wrap elements in the sortable class els = document.querySelectorAll('[hashedit-sortable] > *'); // wrap editable items for (y = 0; y < els.length; y += 1) { hashedit.setupElementMenu(els[y]); } // get all sortable elements els = document.querySelectorAll('[hashedit] [hashedit-sortable]'); // walk through elements for (x = 0; x < els.length; x += 1) { el = els[x]; obj = new Sortable(el, { group: "hashedit-sortable", // or { name: "...", pull: [true, false, clone], put: [true, false, array] } sort: true, // sorting inside list delay: 0, // time in milliseconds to define when the sorting should start disabled: false, // Disables the sortable if set to true. store: null, // @see Store animation: 150, // ms, animation speed moving items when sorting, `0` — without animation handle: ".hashedit-move", // Drag handle selector within list items ghostClass: "hashedit-highlight", // Class name for the drop placeholder scroll: true, // or HTMLElement scrollSensitivity: 30, // px, how near the mouse must be to an edge to start scrolling. scrollSpeed: 10, // px // dragging ended onEnd: function(evt) { // get item item = evt.item; // handle empty hashedit.setupEmpty(); } }); } // set the display of empty columns hashedit.setupEmpty(); }
[ "function", "(", ")", "{", "var", "x", ",", "y", ",", "els", ",", "div", ",", "span", ",", "el", ",", "item", ",", "obj", ",", "menu", ",", "sortable", ",", "a", ";", "sortable", "=", "hashedit", ".", "config", ".", "sortable", ";", "for", "(", "x", "=", "0", ";", "x", "<", "sortable", ".", "length", ";", "x", "+=", "1", ")", "{", "els", "=", "document", ".", "querySelectorAll", "(", "'[hashedit] '", "+", "sortable", "[", "x", "]", ")", ";", "for", "(", "y", "=", "0", ";", "y", "<", "els", ".", "length", ";", "y", "+=", "1", ")", "{", "els", "[", "y", "]", ".", "setAttribute", "(", "'hashedit-sortable'", ",", "''", ")", ";", "}", "}", "els", "=", "document", ".", "querySelectorAll", "(", "'[hashedit-sortable] > *'", ")", ";", "for", "(", "y", "=", "0", ";", "y", "<", "els", ".", "length", ";", "y", "+=", "1", ")", "{", "hashedit", ".", "setupElementMenu", "(", "els", "[", "y", "]", ")", ";", "}", "els", "=", "document", ".", "querySelectorAll", "(", "'[hashedit] [hashedit-sortable]'", ")", ";", "for", "(", "x", "=", "0", ";", "x", "<", "els", ".", "length", ";", "x", "+=", "1", ")", "{", "el", "=", "els", "[", "x", "]", ";", "obj", "=", "new", "Sortable", "(", "el", ",", "{", "group", ":", "\"hashedit-sortable\"", ",", "sort", ":", "true", ",", "delay", ":", "0", ",", "disabled", ":", "false", ",", "store", ":", "null", ",", "animation", ":", "150", ",", "handle", ":", "\".hashedit-move\"", ",", "ghostClass", ":", "\"hashedit-highlight\"", ",", "scroll", ":", "true", ",", "scrollSensitivity", ":", "30", ",", "scrollSpeed", ":", "10", ",", "onEnd", ":", "function", "(", "evt", ")", "{", "item", "=", "evt", ".", "item", ";", "hashedit", ".", "setupEmpty", "(", ")", ";", "}", "}", ")", ";", "}", "hashedit", ".", "setupEmpty", "(", ")", ";", "}" ]
Adds a hashedit-sortable class to any selector in the sortable array, enables sorting @param {Array} sortable
[ "Adds", "a", "hashedit", "-", "sortable", "class", "to", "any", "selector", "in", "the", "sortable", "array", "enables", "sorting" ]
14b5570cc7a97f8bdcfa596ce27260d25f8e18da
https://github.com/madoublet/hashedit/blob/14b5570cc7a97f8bdcfa596ce27260d25f8e18da/dist/hashedit.js#L299-L371
train
madoublet/hashedit
dist/hashedit.js
function() { var menu, data, xhr, url, help, els, x, title = '', arr; // create menu menu = document.createElement('menu'); menu.setAttribute('class', 'hashedit-menu'); menu.innerHTML = '<div class="hashedit-menu-body"></div>'; // append menu hashedit.current.container.appendChild(menu); // focused if(document.querySelector('.hashedit-focused') != null) { var el = document.querySelector('.hashedit-focused'); if(document.querySelector('[focused-content]') == null) { el.style.display = 'none'; } el.addEventListener('click', function(e) { var url = window.location.href.replace('mode=page', 'mode=focused'); //location.href = url; var iframe = window.parent.document.getElementsByTagName('iframe')[0]; iframe.setAttribute('src', url); console.log(iframe); }); } }
javascript
function() { var menu, data, xhr, url, help, els, x, title = '', arr; // create menu menu = document.createElement('menu'); menu.setAttribute('class', 'hashedit-menu'); menu.innerHTML = '<div class="hashedit-menu-body"></div>'; // append menu hashedit.current.container.appendChild(menu); // focused if(document.querySelector('.hashedit-focused') != null) { var el = document.querySelector('.hashedit-focused'); if(document.querySelector('[focused-content]') == null) { el.style.display = 'none'; } el.addEventListener('click', function(e) { var url = window.location.href.replace('mode=page', 'mode=focused'); //location.href = url; var iframe = window.parent.document.getElementsByTagName('iframe')[0]; iframe.setAttribute('src', url); console.log(iframe); }); } }
[ "function", "(", ")", "{", "var", "menu", ",", "data", ",", "xhr", ",", "url", ",", "help", ",", "els", ",", "x", ",", "title", "=", "''", ",", "arr", ";", "menu", "=", "document", ".", "createElement", "(", "'menu'", ")", ";", "menu", ".", "setAttribute", "(", "'class'", ",", "'hashedit-menu'", ")", ";", "menu", ".", "innerHTML", "=", "'<div class=\"hashedit-menu-body\"></div>'", ";", "hashedit", ".", "current", ".", "container", ".", "appendChild", "(", "menu", ")", ";", "if", "(", "document", ".", "querySelector", "(", "'.hashedit-focused'", ")", "!=", "null", ")", "{", "var", "el", "=", "document", ".", "querySelector", "(", "'.hashedit-focused'", ")", ";", "if", "(", "document", ".", "querySelector", "(", "'[focused-content]'", ")", "==", "null", ")", "{", "el", ".", "style", ".", "display", "=", "'none'", ";", "}", "el", ".", "addEventListener", "(", "'click'", ",", "function", "(", "e", ")", "{", "var", "url", "=", "window", ".", "location", ".", "href", ".", "replace", "(", "'mode=page'", ",", "'mode=focused'", ")", ";", "var", "iframe", "=", "window", ".", "parent", ".", "document", ".", "getElementsByTagName", "(", "'iframe'", ")", "[", "0", "]", ";", "iframe", ".", "setAttribute", "(", "'src'", ",", "url", ")", ";", "console", ".", "log", "(", "iframe", ")", ";", "}", ")", ";", "}", "}" ]
Create the menu
[ "Create", "the", "menu" ]
14b5570cc7a97f8bdcfa596ce27260d25f8e18da
https://github.com/madoublet/hashedit/blob/14b5570cc7a97f8bdcfa596ce27260d25f8e18da/dist/hashedit.js#L376-L413
train
madoublet/hashedit
dist/hashedit.js
function() { var menu = document.querySelector('.hashedit-menu'); if(menu.hasAttribute('active') == true) { menu.removeAttribute('active'); } else { menu.setAttribute('active', true); } }
javascript
function() { var menu = document.querySelector('.hashedit-menu'); if(menu.hasAttribute('active') == true) { menu.removeAttribute('active'); } else { menu.setAttribute('active', true); } }
[ "function", "(", ")", "{", "var", "menu", "=", "document", ".", "querySelector", "(", "'.hashedit-menu'", ")", ";", "if", "(", "menu", ".", "hasAttribute", "(", "'active'", ")", "==", "true", ")", "{", "menu", ".", "removeAttribute", "(", "'active'", ")", ";", "}", "else", "{", "menu", ".", "setAttribute", "(", "'active'", ",", "true", ")", ";", "}", "}" ]
Shows the menu
[ "Shows", "the", "menu" ]
14b5570cc7a97f8bdcfa596ce27260d25f8e18da
https://github.com/madoublet/hashedit/blob/14b5570cc7a97f8bdcfa596ce27260d25f8e18da/dist/hashedit.js#L418-L429
train
madoublet/hashedit
dist/hashedit.js
function() { var data, xhr; data = hashedit.retrieveUpdateArray(); if (hashedit.saveUrl) { // construct an HTTP request xhr = new XMLHttpRequest(); xhr.open('post', hashedit.saveUrl, true); // set token if(hashedit.useToken == true) { xhr.setRequestHeader(hashedit.authHeader, hashedit.authHeaderPrefix + ' ' + localStorage.getItem(hashedit.tokenName)); } // send the collected data as JSON xhr.send(JSON.stringify(data)); xhr.onloadend = function() { location.reload(); }; } }
javascript
function() { var data, xhr; data = hashedit.retrieveUpdateArray(); if (hashedit.saveUrl) { // construct an HTTP request xhr = new XMLHttpRequest(); xhr.open('post', hashedit.saveUrl, true); // set token if(hashedit.useToken == true) { xhr.setRequestHeader(hashedit.authHeader, hashedit.authHeaderPrefix + ' ' + localStorage.getItem(hashedit.tokenName)); } // send the collected data as JSON xhr.send(JSON.stringify(data)); xhr.onloadend = function() { location.reload(); }; } }
[ "function", "(", ")", "{", "var", "data", ",", "xhr", ";", "data", "=", "hashedit", ".", "retrieveUpdateArray", "(", ")", ";", "if", "(", "hashedit", ".", "saveUrl", ")", "{", "xhr", "=", "new", "XMLHttpRequest", "(", ")", ";", "xhr", ".", "open", "(", "'post'", ",", "hashedit", ".", "saveUrl", ",", "true", ")", ";", "if", "(", "hashedit", ".", "useToken", "==", "true", ")", "{", "xhr", ".", "setRequestHeader", "(", "hashedit", ".", "authHeader", ",", "hashedit", ".", "authHeaderPrefix", "+", "' '", "+", "localStorage", ".", "getItem", "(", "hashedit", ".", "tokenName", ")", ")", ";", "}", "xhr", ".", "send", "(", "JSON", ".", "stringify", "(", "data", ")", ")", ";", "xhr", ".", "onloadend", "=", "function", "(", ")", "{", "location", ".", "reload", "(", ")", ";", "}", ";", "}", "}" ]
Saves the content
[ "Saves", "the", "content" ]
14b5570cc7a97f8bdcfa596ce27260d25f8e18da
https://github.com/madoublet/hashedit/blob/14b5570cc7a97f8bdcfa596ce27260d25f8e18da/dist/hashedit.js#L434-L462
train
madoublet/hashedit
dist/hashedit.js
function() { var x, el, selector, sortable, item, action, html; // setup sortable on the menu el = document.querySelector('.hashedit-menu-body'); sortable = new Sortable(el, { group: { name: 'hashedit-sortable', pull: 'clone', put: false }, draggable: 'a', sort: false, // sorting inside list delay: 0, // time in milliseconds to define when the sorting should start disabled: false, // Disables the sortable if set to true. animation: 150, // ms, animation speed moving items when sorting, `0` — without animation ghostClass: "hashedit-highlight", // Class name for the drop placeholder scroll: true, // or HTMLElement scrollSensitivity: 30, // px, how near the mouse must be to an edge to start scrolling. scrollSpeed: 10, // px onStart: function(evt) { document.querySelector('.hashedit-menu').removeAttribute('active'); }, // dragging ended onEnd: function(evt) { // get item item = evt.item; if (hashedit.debug === true) { console.log(item); } // get action selector = item.getAttribute('data-selector'); // append html associated with action for (x = 0; x < hashedit.menu.length; x += 1) { if (hashedit.menu[x].selector == selector) { html = hashedit.menu[x].html; html = hashedit.replaceAll(html, '{{path}}', hashedit.path); html = hashedit.replaceAll(html, '{{framework.image}}', hashedit.frameworkDefaults[hashedit.framework].image); html = hashedit.replaceAll(html, '{{framework.table}}', hashedit.frameworkDefaults[hashedit.framework].table); html = hashedit.replaceAll(html, '{{framework.code}}', hashedit.frameworkDefaults[hashedit.framework].code); var node = hashedit.append(html); // add if(hashedit.menu[x].view != undefined) { node.innerHTML += hashedit.menu[x].view; } } } // setup empty columns hashedit.setupEmpty(); // remove help var help = document.querySelector('.hashedit-help'); if(help != null) { help.innerHTML = ''; help.removeAttribute('active'); } return false; } }); }
javascript
function() { var x, el, selector, sortable, item, action, html; // setup sortable on the menu el = document.querySelector('.hashedit-menu-body'); sortable = new Sortable(el, { group: { name: 'hashedit-sortable', pull: 'clone', put: false }, draggable: 'a', sort: false, // sorting inside list delay: 0, // time in milliseconds to define when the sorting should start disabled: false, // Disables the sortable if set to true. animation: 150, // ms, animation speed moving items when sorting, `0` — without animation ghostClass: "hashedit-highlight", // Class name for the drop placeholder scroll: true, // or HTMLElement scrollSensitivity: 30, // px, how near the mouse must be to an edge to start scrolling. scrollSpeed: 10, // px onStart: function(evt) { document.querySelector('.hashedit-menu').removeAttribute('active'); }, // dragging ended onEnd: function(evt) { // get item item = evt.item; if (hashedit.debug === true) { console.log(item); } // get action selector = item.getAttribute('data-selector'); // append html associated with action for (x = 0; x < hashedit.menu.length; x += 1) { if (hashedit.menu[x].selector == selector) { html = hashedit.menu[x].html; html = hashedit.replaceAll(html, '{{path}}', hashedit.path); html = hashedit.replaceAll(html, '{{framework.image}}', hashedit.frameworkDefaults[hashedit.framework].image); html = hashedit.replaceAll(html, '{{framework.table}}', hashedit.frameworkDefaults[hashedit.framework].table); html = hashedit.replaceAll(html, '{{framework.code}}', hashedit.frameworkDefaults[hashedit.framework].code); var node = hashedit.append(html); // add if(hashedit.menu[x].view != undefined) { node.innerHTML += hashedit.menu[x].view; } } } // setup empty columns hashedit.setupEmpty(); // remove help var help = document.querySelector('.hashedit-help'); if(help != null) { help.innerHTML = ''; help.removeAttribute('active'); } return false; } }); }
[ "function", "(", ")", "{", "var", "x", ",", "el", ",", "selector", ",", "sortable", ",", "item", ",", "action", ",", "html", ";", "el", "=", "document", ".", "querySelector", "(", "'.hashedit-menu-body'", ")", ";", "sortable", "=", "new", "Sortable", "(", "el", ",", "{", "group", ":", "{", "name", ":", "'hashedit-sortable'", ",", "pull", ":", "'clone'", ",", "put", ":", "false", "}", ",", "draggable", ":", "'a'", ",", "sort", ":", "false", ",", "delay", ":", "0", ",", "disabled", ":", "false", ",", "animation", ":", "150", ",", "ghostClass", ":", "\"hashedit-highlight\"", ",", "scroll", ":", "true", ",", "scrollSensitivity", ":", "30", ",", "scrollSpeed", ":", "10", ",", "onStart", ":", "function", "(", "evt", ")", "{", "document", ".", "querySelector", "(", "'.hashedit-menu'", ")", ".", "removeAttribute", "(", "'active'", ")", ";", "}", ",", "onEnd", ":", "function", "(", "evt", ")", "{", "item", "=", "evt", ".", "item", ";", "if", "(", "hashedit", ".", "debug", "===", "true", ")", "{", "console", ".", "log", "(", "item", ")", ";", "}", "selector", "=", "item", ".", "getAttribute", "(", "'data-selector'", ")", ";", "for", "(", "x", "=", "0", ";", "x", "<", "hashedit", ".", "menu", ".", "length", ";", "x", "+=", "1", ")", "{", "if", "(", "hashedit", ".", "menu", "[", "x", "]", ".", "selector", "==", "selector", ")", "{", "html", "=", "hashedit", ".", "menu", "[", "x", "]", ".", "html", ";", "html", "=", "hashedit", ".", "replaceAll", "(", "html", ",", "'{{path}}'", ",", "hashedit", ".", "path", ")", ";", "html", "=", "hashedit", ".", "replaceAll", "(", "html", ",", "'{{framework.image}}'", ",", "hashedit", ".", "frameworkDefaults", "[", "hashedit", ".", "framework", "]", ".", "image", ")", ";", "html", "=", "hashedit", ".", "replaceAll", "(", "html", ",", "'{{framework.table}}'", ",", "hashedit", ".", "frameworkDefaults", "[", "hashedit", ".", "framework", "]", ".", "table", ")", ";", "html", "=", "hashedit", ".", "replaceAll", "(", "html", ",", "'{{framework.code}}'", ",", "hashedit", ".", "frameworkDefaults", "[", "hashedit", ".", "framework", "]", ".", "code", ")", ";", "var", "node", "=", "hashedit", ".", "append", "(", "html", ")", ";", "if", "(", "hashedit", ".", "menu", "[", "x", "]", ".", "view", "!=", "undefined", ")", "{", "node", ".", "innerHTML", "+=", "hashedit", ".", "menu", "[", "x", "]", ".", "view", ";", "}", "}", "}", "hashedit", ".", "setupEmpty", "(", ")", ";", "var", "help", "=", "document", ".", "querySelector", "(", "'.hashedit-help'", ")", ";", "if", "(", "help", "!=", "null", ")", "{", "help", ".", "innerHTML", "=", "''", ";", "help", ".", "removeAttribute", "(", "'active'", ")", ";", "}", "return", "false", ";", "}", "}", ")", ";", "}" ]
Setup draggable events on menu items
[ "Setup", "draggable", "events", "on", "menu", "items" ]
14b5570cc7a97f8bdcfa596ce27260d25f8e18da
https://github.com/madoublet/hashedit/blob/14b5570cc7a97f8bdcfa596ce27260d25f8e18da/dist/hashedit.js#L467-L544
train
madoublet/hashedit
dist/hashedit.js
function(element) { var x, link, image, text, fields; // set current element and node hashedit.current.element = element; hashedit.current.node = element; // if the current element is not a [hashedit-element], find the parent that matches if(hashedit.current.element.hasAttribute('hashedit-element') === false) { hashedit.current.element = hashedit.findParentBySelector(element, '[hashedit-element]'); } // hide #hashedit-image image = document.querySelector('#hashedit-image-settings-modal'); image.removeAttribute('visible'); // hide #hashedit-link link = document.querySelector('#hashedit-link-settings-modal'); link.removeAttribute('visible'); // get #hashedit-config text = document.querySelector('#hashedit-text-settings'); text.setAttribute('visible', ''); // clear form fields fields = document.querySelectorAll('[data-model]'); for (x = 0; x < fields.length; x += 1) { if (fields[x].nodeType == 'SELECT') { fields[x].selectedIndex = 0; } else { fields[x].value = ''; } } hashedit.bind(); }
javascript
function(element) { var x, link, image, text, fields; // set current element and node hashedit.current.element = element; hashedit.current.node = element; // if the current element is not a [hashedit-element], find the parent that matches if(hashedit.current.element.hasAttribute('hashedit-element') === false) { hashedit.current.element = hashedit.findParentBySelector(element, '[hashedit-element]'); } // hide #hashedit-image image = document.querySelector('#hashedit-image-settings-modal'); image.removeAttribute('visible'); // hide #hashedit-link link = document.querySelector('#hashedit-link-settings-modal'); link.removeAttribute('visible'); // get #hashedit-config text = document.querySelector('#hashedit-text-settings'); text.setAttribute('visible', ''); // clear form fields fields = document.querySelectorAll('[data-model]'); for (x = 0; x < fields.length; x += 1) { if (fields[x].nodeType == 'SELECT') { fields[x].selectedIndex = 0; } else { fields[x].value = ''; } } hashedit.bind(); }
[ "function", "(", "element", ")", "{", "var", "x", ",", "link", ",", "image", ",", "text", ",", "fields", ";", "hashedit", ".", "current", ".", "element", "=", "element", ";", "hashedit", ".", "current", ".", "node", "=", "element", ";", "if", "(", "hashedit", ".", "current", ".", "element", ".", "hasAttribute", "(", "'hashedit-element'", ")", "===", "false", ")", "{", "hashedit", ".", "current", ".", "element", "=", "hashedit", ".", "findParentBySelector", "(", "element", ",", "'[hashedit-element]'", ")", ";", "}", "image", "=", "document", ".", "querySelector", "(", "'#hashedit-image-settings-modal'", ")", ";", "image", ".", "removeAttribute", "(", "'visible'", ")", ";", "link", "=", "document", ".", "querySelector", "(", "'#hashedit-link-settings-modal'", ")", ";", "link", ".", "removeAttribute", "(", "'visible'", ")", ";", "text", "=", "document", ".", "querySelector", "(", "'#hashedit-text-settings'", ")", ";", "text", ".", "setAttribute", "(", "'visible'", ",", "''", ")", ";", "fields", "=", "document", ".", "querySelectorAll", "(", "'[data-model]'", ")", ";", "for", "(", "x", "=", "0", ";", "x", "<", "fields", ".", "length", ";", "x", "+=", "1", ")", "{", "if", "(", "fields", "[", "x", "]", ".", "nodeType", "==", "'SELECT'", ")", "{", "fields", "[", "x", "]", ".", "selectedIndex", "=", "0", ";", "}", "else", "{", "fields", "[", "x", "]", ".", "value", "=", "''", ";", "}", "}", "hashedit", ".", "bind", "(", ")", ";", "}" ]
Shows the text options
[ "Shows", "the", "text", "options" ]
14b5570cc7a97f8bdcfa596ce27260d25f8e18da
https://github.com/madoublet/hashedit/blob/14b5570cc7a97f8bdcfa596ce27260d25f8e18da/dist/hashedit.js#L866-L904
train
madoublet/hashedit
dist/hashedit.js
function() { var attrs, x, y, z, key, value, html, inputs, textarea; console.log(hashedit.current.node); if (hashedit.current.node !== null) { // get attributes attrs = hashedit.current.node.attributes; for (x = 0; x < attrs.length; x += 1) { // get key and value key = attrs[x].nodeName.replace(/-([a-z])/g, function(g) { return g[1].toUpperCase(); }); value = attrs[x].nodeValue; // if is numeric if (!isNaN(parseFloat(value)) && isFinite(value)) { value = parseFloat(value); } // set value inputs = document.querySelectorAll('[data-model="node.' + key + '"]'); for (y = 0; y < inputs.length; y += 1) { inputs[y].value = value; } } // get html html = hashedit.current.node.innerHTML; // remove the element menu var i = html.indexOf('<span class="hashedit-element-menu"'); html = html.substring(0, i); inputs = document.querySelectorAll('[data-model="node.html"]'); for (y = 0; y < inputs.length; y += 1) { inputs[y].value = html; } } }
javascript
function() { var attrs, x, y, z, key, value, html, inputs, textarea; console.log(hashedit.current.node); if (hashedit.current.node !== null) { // get attributes attrs = hashedit.current.node.attributes; for (x = 0; x < attrs.length; x += 1) { // get key and value key = attrs[x].nodeName.replace(/-([a-z])/g, function(g) { return g[1].toUpperCase(); }); value = attrs[x].nodeValue; // if is numeric if (!isNaN(parseFloat(value)) && isFinite(value)) { value = parseFloat(value); } // set value inputs = document.querySelectorAll('[data-model="node.' + key + '"]'); for (y = 0; y < inputs.length; y += 1) { inputs[y].value = value; } } // get html html = hashedit.current.node.innerHTML; // remove the element menu var i = html.indexOf('<span class="hashedit-element-menu"'); html = html.substring(0, i); inputs = document.querySelectorAll('[data-model="node.html"]'); for (y = 0; y < inputs.length; y += 1) { inputs[y].value = html; } } }
[ "function", "(", ")", "{", "var", "attrs", ",", "x", ",", "y", ",", "z", ",", "key", ",", "value", ",", "html", ",", "inputs", ",", "textarea", ";", "console", ".", "log", "(", "hashedit", ".", "current", ".", "node", ")", ";", "if", "(", "hashedit", ".", "current", ".", "node", "!==", "null", ")", "{", "attrs", "=", "hashedit", ".", "current", ".", "node", ".", "attributes", ";", "for", "(", "x", "=", "0", ";", "x", "<", "attrs", ".", "length", ";", "x", "+=", "1", ")", "{", "key", "=", "attrs", "[", "x", "]", ".", "nodeName", ".", "replace", "(", "/", "-([a-z])", "/", "g", ",", "function", "(", "g", ")", "{", "return", "g", "[", "1", "]", ".", "toUpperCase", "(", ")", ";", "}", ")", ";", "value", "=", "attrs", "[", "x", "]", ".", "nodeValue", ";", "if", "(", "!", "isNaN", "(", "parseFloat", "(", "value", ")", ")", "&&", "isFinite", "(", "value", ")", ")", "{", "value", "=", "parseFloat", "(", "value", ")", ";", "}", "inputs", "=", "document", ".", "querySelectorAll", "(", "'[data-model=\"node.'", "+", "key", "+", "'\"]'", ")", ";", "for", "(", "y", "=", "0", ";", "y", "<", "inputs", ".", "length", ";", "y", "+=", "1", ")", "{", "inputs", "[", "y", "]", ".", "value", "=", "value", ";", "}", "}", "html", "=", "hashedit", ".", "current", ".", "node", ".", "innerHTML", ";", "var", "i", "=", "html", ".", "indexOf", "(", "'<span class=\"hashedit-element-menu\"'", ")", ";", "html", "=", "html", ".", "substring", "(", "0", ",", "i", ")", ";", "inputs", "=", "document", ".", "querySelectorAll", "(", "'[data-model=\"node.html\"]'", ")", ";", "for", "(", "y", "=", "0", ";", "y", "<", "inputs", ".", "length", ";", "y", "+=", "1", ")", "{", "inputs", "[", "y", "]", ".", "value", "=", "html", ";", "}", "}", "}" ]
Binds data from the current element
[ "Binds", "data", "from", "the", "current", "element" ]
14b5570cc7a97f8bdcfa596ce27260d25f8e18da
https://github.com/madoublet/hashedit/blob/14b5570cc7a97f8bdcfa596ce27260d25f8e18da/dist/hashedit.js#L909-L959
train
madoublet/hashedit
dist/hashedit.js
function(el) { var text = ''; for (var i = 0; i < el.childNodes.length; i++) { var curNode = el.childNodes[i]; var whitespace = /^\s*$/; if(curNode === undefined) { text = ""; break; } if (curNode.nodeName === "#text" && !(whitespace.test(curNode.nodeValue))) { text = curNode.nodeValue; break; } } return text; }
javascript
function(el) { var text = ''; for (var i = 0; i < el.childNodes.length; i++) { var curNode = el.childNodes[i]; var whitespace = /^\s*$/; if(curNode === undefined) { text = ""; break; } if (curNode.nodeName === "#text" && !(whitespace.test(curNode.nodeValue))) { text = curNode.nodeValue; break; } } return text; }
[ "function", "(", "el", ")", "{", "var", "text", "=", "''", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "el", ".", "childNodes", ".", "length", ";", "i", "++", ")", "{", "var", "curNode", "=", "el", ".", "childNodes", "[", "i", "]", ";", "var", "whitespace", "=", "/", "^\\s*$", "/", ";", "if", "(", "curNode", "===", "undefined", ")", "{", "text", "=", "\"\"", ";", "break", ";", "}", "if", "(", "curNode", ".", "nodeName", "===", "\"#text\"", "&&", "!", "(", "whitespace", ".", "test", "(", "curNode", ".", "nodeValue", ")", ")", ")", "{", "text", "=", "curNode", ".", "nodeValue", ";", "break", ";", "}", "}", "return", "text", ";", "}" ]
Returns the value of the text node
[ "Returns", "the", "value", "of", "the", "text", "node" ]
14b5570cc7a97f8bdcfa596ce27260d25f8e18da
https://github.com/madoublet/hashedit/blob/14b5570cc7a97f8bdcfa596ce27260d25f8e18da/dist/hashedit.js#L1437-L1458
train
madoublet/hashedit
dist/hashedit.js
function(html) { var x, newNode, node, firstChild; // create a new node newNode = document.createElement('div'); newNode.innerHTML = html; // get new new node newNode = newNode.childNodes[0]; newNode.setAttribute('hashedit-element', ''); hashedit.setupElementMenu(newNode); // get existing node node = document.querySelector('[hashedit-sortable] [data-selector]'); if (node === null) { if (hashedit.current.node !== null) { // insert after current node hashedit.current.node.parentNode.insertBefore(newNode, hashedit.current.node.nextSibling); } } else { // replace existing node with newNode node.parentNode.replaceChild(newNode, node); } var types = 'p, h1, h2, h3, h4, h5, li, td, th, blockquote, pre'; // set editable children var editable = newNode.querySelectorAll(types); for (x = 0; x < editable.length; x += 1) { editable[x].setAttribute('contentEditable', 'true'); } if (types.indexOf(newNode.nodeName.toLowerCase()) != -1) { newNode.setAttribute('contentEditable', 'true'); } // select element function selectElementContents(el) { var range = document.createRange(); range.selectNodeContents(el); var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); } // focus on first element if (editable.length > 0) { editable[0].focus(); selectElementContents(editable[0]); // show edit options for the text hashedit.showTextOptions(editable[0]); // select editable contents, #ref: http://bit.ly/1jxd8er hashedit.selectElementContents(editable[0]); } else { if(newNode.matches(types)) { newNode.focus(); selectElementContents(newNode); } } return newNode; }
javascript
function(html) { var x, newNode, node, firstChild; // create a new node newNode = document.createElement('div'); newNode.innerHTML = html; // get new new node newNode = newNode.childNodes[0]; newNode.setAttribute('hashedit-element', ''); hashedit.setupElementMenu(newNode); // get existing node node = document.querySelector('[hashedit-sortable] [data-selector]'); if (node === null) { if (hashedit.current.node !== null) { // insert after current node hashedit.current.node.parentNode.insertBefore(newNode, hashedit.current.node.nextSibling); } } else { // replace existing node with newNode node.parentNode.replaceChild(newNode, node); } var types = 'p, h1, h2, h3, h4, h5, li, td, th, blockquote, pre'; // set editable children var editable = newNode.querySelectorAll(types); for (x = 0; x < editable.length; x += 1) { editable[x].setAttribute('contentEditable', 'true'); } if (types.indexOf(newNode.nodeName.toLowerCase()) != -1) { newNode.setAttribute('contentEditable', 'true'); } // select element function selectElementContents(el) { var range = document.createRange(); range.selectNodeContents(el); var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); } // focus on first element if (editable.length > 0) { editable[0].focus(); selectElementContents(editable[0]); // show edit options for the text hashedit.showTextOptions(editable[0]); // select editable contents, #ref: http://bit.ly/1jxd8er hashedit.selectElementContents(editable[0]); } else { if(newNode.matches(types)) { newNode.focus(); selectElementContents(newNode); } } return newNode; }
[ "function", "(", "html", ")", "{", "var", "x", ",", "newNode", ",", "node", ",", "firstChild", ";", "newNode", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "newNode", ".", "innerHTML", "=", "html", ";", "newNode", "=", "newNode", ".", "childNodes", "[", "0", "]", ";", "newNode", ".", "setAttribute", "(", "'hashedit-element'", ",", "''", ")", ";", "hashedit", ".", "setupElementMenu", "(", "newNode", ")", ";", "node", "=", "document", ".", "querySelector", "(", "'[hashedit-sortable] [data-selector]'", ")", ";", "if", "(", "node", "===", "null", ")", "{", "if", "(", "hashedit", ".", "current", ".", "node", "!==", "null", ")", "{", "hashedit", ".", "current", ".", "node", ".", "parentNode", ".", "insertBefore", "(", "newNode", ",", "hashedit", ".", "current", ".", "node", ".", "nextSibling", ")", ";", "}", "}", "else", "{", "node", ".", "parentNode", ".", "replaceChild", "(", "newNode", ",", "node", ")", ";", "}", "var", "types", "=", "'p, h1, h2, h3, h4, h5, li, td, th, blockquote, pre'", ";", "var", "editable", "=", "newNode", ".", "querySelectorAll", "(", "types", ")", ";", "for", "(", "x", "=", "0", ";", "x", "<", "editable", ".", "length", ";", "x", "+=", "1", ")", "{", "editable", "[", "x", "]", ".", "setAttribute", "(", "'contentEditable'", ",", "'true'", ")", ";", "}", "if", "(", "types", ".", "indexOf", "(", "newNode", ".", "nodeName", ".", "toLowerCase", "(", ")", ")", "!=", "-", "1", ")", "{", "newNode", ".", "setAttribute", "(", "'contentEditable'", ",", "'true'", ")", ";", "}", "function", "selectElementContents", "(", "el", ")", "{", "var", "range", "=", "document", ".", "createRange", "(", ")", ";", "range", ".", "selectNodeContents", "(", "el", ")", ";", "var", "sel", "=", "window", ".", "getSelection", "(", ")", ";", "sel", ".", "removeAllRanges", "(", ")", ";", "sel", ".", "addRange", "(", "range", ")", ";", "}", "if", "(", "editable", ".", "length", ">", "0", ")", "{", "editable", "[", "0", "]", ".", "focus", "(", ")", ";", "selectElementContents", "(", "editable", "[", "0", "]", ")", ";", "hashedit", ".", "showTextOptions", "(", "editable", "[", "0", "]", ")", ";", "hashedit", ".", "selectElementContents", "(", "editable", "[", "0", "]", ")", ";", "}", "else", "{", "if", "(", "newNode", ".", "matches", "(", "types", ")", ")", "{", "newNode", ".", "focus", "(", ")", ";", "selectElementContents", "(", "newNode", ")", ";", "}", "}", "return", "newNode", ";", "}" ]
Appends items to the editor
[ "Appends", "items", "to", "the", "editor" ]
14b5570cc7a97f8bdcfa596ce27260d25f8e18da
https://github.com/madoublet/hashedit/blob/14b5570cc7a97f8bdcfa596ce27260d25f8e18da/dist/hashedit.js#L1476-L1555
train
madoublet/hashedit
dist/hashedit.js
function(current, position) { var x, newNode, node, firstChild; // create a new node newNode = current.cloneNode(true); // create new node in mirror if (position == 'before') { // insert element current.parentNode.insertBefore(newNode, current); } // re-init sortable hashedit.setupSortable(); return newNode; }
javascript
function(current, position) { var x, newNode, node, firstChild; // create a new node newNode = current.cloneNode(true); // create new node in mirror if (position == 'before') { // insert element current.parentNode.insertBefore(newNode, current); } // re-init sortable hashedit.setupSortable(); return newNode; }
[ "function", "(", "current", ",", "position", ")", "{", "var", "x", ",", "newNode", ",", "node", ",", "firstChild", ";", "newNode", "=", "current", ".", "cloneNode", "(", "true", ")", ";", "if", "(", "position", "==", "'before'", ")", "{", "current", ".", "parentNode", ".", "insertBefore", "(", "newNode", ",", "current", ")", ";", "}", "hashedit", ".", "setupSortable", "(", ")", ";", "return", "newNode", ";", "}" ]
Duplicates a block and appends it to the editor
[ "Duplicates", "a", "block", "and", "appends", "it", "to", "the", "editor" ]
14b5570cc7a97f8bdcfa596ce27260d25f8e18da
https://github.com/madoublet/hashedit/blob/14b5570cc7a97f8bdcfa596ce27260d25f8e18da/dist/hashedit.js#L1560-L1580
train
madoublet/hashedit
dist/hashedit.js
function(html, current, position) { var x, newNode, node, firstChild; // create a new node newNode = document.createElement('div'); newNode.innerHTML = html; // get new new node newNode = newNode.childNodes[0]; // create new node in mirror if (position == 'before') { // insert element current.parentNode.insertBefore(newNode, current); } // re-init sortable hashedit.setupSortable(); return newNode; }
javascript
function(html, current, position) { var x, newNode, node, firstChild; // create a new node newNode = document.createElement('div'); newNode.innerHTML = html; // get new new node newNode = newNode.childNodes[0]; // create new node in mirror if (position == 'before') { // insert element current.parentNode.insertBefore(newNode, current); } // re-init sortable hashedit.setupSortable(); return newNode; }
[ "function", "(", "html", ",", "current", ",", "position", ")", "{", "var", "x", ",", "newNode", ",", "node", ",", "firstChild", ";", "newNode", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "newNode", ".", "innerHTML", "=", "html", ";", "newNode", "=", "newNode", ".", "childNodes", "[", "0", "]", ";", "if", "(", "position", "==", "'before'", ")", "{", "current", ".", "parentNode", ".", "insertBefore", "(", "newNode", ",", "current", ")", ";", "}", "hashedit", ".", "setupSortable", "(", ")", ";", "return", "newNode", ";", "}" ]
Appends blocks to the editor
[ "Appends", "blocks", "to", "the", "editor" ]
14b5570cc7a97f8bdcfa596ce27260d25f8e18da
https://github.com/madoublet/hashedit/blob/14b5570cc7a97f8bdcfa596ce27260d25f8e18da/dist/hashedit.js#L1585-L1609
train
madoublet/hashedit
dist/hashedit.js
function() { var id, cssClass, href, target, title, link; // get selected link hashedit.currLink = hashedit.getLinkFromSelection(); // populate link values if (hashedit.currLink !== null) { // get attributes id = hashedit.currLink.getAttribute('id') || ''; cssClass = hashedit.currLink.getAttribute('class') || ''; href = hashedit.currLink.getAttribute('href') || ''; target = hashedit.currLink.getAttribute('target') || ''; title = hashedit.currLink.getAttribute('title') || ''; // show the link dialog link = document.querySelector('#hashedit-link-settings-modal'); link.setAttribute('visible', ''); // sets start values document.getElementById('hashedit-link-id').value = id; document.getElementById('hashedit-link-cssclass').value = cssClass; document.getElementById('hashedit-link-href').value = href; document.getElementById('hashedit-link-target').value = target; document.getElementById('hashedit-link-title').value = title; } }
javascript
function() { var id, cssClass, href, target, title, link; // get selected link hashedit.currLink = hashedit.getLinkFromSelection(); // populate link values if (hashedit.currLink !== null) { // get attributes id = hashedit.currLink.getAttribute('id') || ''; cssClass = hashedit.currLink.getAttribute('class') || ''; href = hashedit.currLink.getAttribute('href') || ''; target = hashedit.currLink.getAttribute('target') || ''; title = hashedit.currLink.getAttribute('title') || ''; // show the link dialog link = document.querySelector('#hashedit-link-settings-modal'); link.setAttribute('visible', ''); // sets start values document.getElementById('hashedit-link-id').value = id; document.getElementById('hashedit-link-cssclass').value = cssClass; document.getElementById('hashedit-link-href').value = href; document.getElementById('hashedit-link-target').value = target; document.getElementById('hashedit-link-title').value = title; } }
[ "function", "(", ")", "{", "var", "id", ",", "cssClass", ",", "href", ",", "target", ",", "title", ",", "link", ";", "hashedit", ".", "currLink", "=", "hashedit", ".", "getLinkFromSelection", "(", ")", ";", "if", "(", "hashedit", ".", "currLink", "!==", "null", ")", "{", "id", "=", "hashedit", ".", "currLink", ".", "getAttribute", "(", "'id'", ")", "||", "''", ";", "cssClass", "=", "hashedit", ".", "currLink", ".", "getAttribute", "(", "'class'", ")", "||", "''", ";", "href", "=", "hashedit", ".", "currLink", ".", "getAttribute", "(", "'href'", ")", "||", "''", ";", "target", "=", "hashedit", ".", "currLink", ".", "getAttribute", "(", "'target'", ")", "||", "''", ";", "title", "=", "hashedit", ".", "currLink", ".", "getAttribute", "(", "'title'", ")", "||", "''", ";", "link", "=", "document", ".", "querySelector", "(", "'#hashedit-link-settings-modal'", ")", ";", "link", ".", "setAttribute", "(", "'visible'", ",", "''", ")", ";", "document", ".", "getElementById", "(", "'hashedit-link-id'", ")", ".", "value", "=", "id", ";", "document", ".", "getElementById", "(", "'hashedit-link-cssclass'", ")", ".", "value", "=", "cssClass", ";", "document", ".", "getElementById", "(", "'hashedit-link-href'", ")", ".", "value", "=", "href", ";", "document", ".", "getElementById", "(", "'hashedit-link-target'", ")", ".", "value", "=", "target", ";", "document", ".", "getElementById", "(", "'hashedit-link-title'", ")", ".", "value", "=", "title", ";", "}", "}" ]
Sets up the link dialog
[ "Sets", "up", "the", "link", "dialog" ]
14b5570cc7a97f8bdcfa596ce27260d25f8e18da
https://github.com/madoublet/hashedit/blob/14b5570cc7a97f8bdcfa596ce27260d25f8e18da/dist/hashedit.js#L2189-L2220
train
madoublet/hashedit
dist/hashedit.js
function(block) { var x, dialog, list, html, el, target, i, items; if(block !== null) { block.setAttribute('hashedit-block-active', ''); } // show the layout dialog dialog = document.querySelector('#hashedit-layout-modal'); // get list list = document.querySelector('#hashedit-layouts-list'); items = list.querySelectorAll('.hashedit-list-item'); // init items if(items.length === 0) { for(x=0; x<hashedit.grid.length; x++) { el = document.createElement('DIV'); el.setAttribute('class', 'hashedit-list-item'); el.setAttribute('data-index', x); el.innerHTML = '<h2>' + hashedit.grid[x].name + '</h2><small>' + hashedit.grid[x].desc + '</small>'; list.appendChild(el); } list.addEventListener('click', function(e) { target = e.target; if(target.nodeName.toUpperCase() !== 'DIV'){ target = hashedit.findParentBySelector(target, '.hashedit-list-item'); } if(target != null) { // append the block i = target.getAttribute('data-index'); html = hashedit.grid[i].html; hashedit.appendBlock(html, block, 'before'); hashedit.setupBlocks(); dialog.removeAttribute('visible'); } }); } dialog.setAttribute('visible', ''); }
javascript
function(block) { var x, dialog, list, html, el, target, i, items; if(block !== null) { block.setAttribute('hashedit-block-active', ''); } // show the layout dialog dialog = document.querySelector('#hashedit-layout-modal'); // get list list = document.querySelector('#hashedit-layouts-list'); items = list.querySelectorAll('.hashedit-list-item'); // init items if(items.length === 0) { for(x=0; x<hashedit.grid.length; x++) { el = document.createElement('DIV'); el.setAttribute('class', 'hashedit-list-item'); el.setAttribute('data-index', x); el.innerHTML = '<h2>' + hashedit.grid[x].name + '</h2><small>' + hashedit.grid[x].desc + '</small>'; list.appendChild(el); } list.addEventListener('click', function(e) { target = e.target; if(target.nodeName.toUpperCase() !== 'DIV'){ target = hashedit.findParentBySelector(target, '.hashedit-list-item'); } if(target != null) { // append the block i = target.getAttribute('data-index'); html = hashedit.grid[i].html; hashedit.appendBlock(html, block, 'before'); hashedit.setupBlocks(); dialog.removeAttribute('visible'); } }); } dialog.setAttribute('visible', ''); }
[ "function", "(", "block", ")", "{", "var", "x", ",", "dialog", ",", "list", ",", "html", ",", "el", ",", "target", ",", "i", ",", "items", ";", "if", "(", "block", "!==", "null", ")", "{", "block", ".", "setAttribute", "(", "'hashedit-block-active'", ",", "''", ")", ";", "}", "dialog", "=", "document", ".", "querySelector", "(", "'#hashedit-layout-modal'", ")", ";", "list", "=", "document", ".", "querySelector", "(", "'#hashedit-layouts-list'", ")", ";", "items", "=", "list", ".", "querySelectorAll", "(", "'.hashedit-list-item'", ")", ";", "if", "(", "items", ".", "length", "===", "0", ")", "{", "for", "(", "x", "=", "0", ";", "x", "<", "hashedit", ".", "grid", ".", "length", ";", "x", "++", ")", "{", "el", "=", "document", ".", "createElement", "(", "'DIV'", ")", ";", "el", ".", "setAttribute", "(", "'class'", ",", "'hashedit-list-item'", ")", ";", "el", ".", "setAttribute", "(", "'data-index'", ",", "x", ")", ";", "el", ".", "innerHTML", "=", "'<h2>'", "+", "hashedit", ".", "grid", "[", "x", "]", ".", "name", "+", "'</h2><small>'", "+", "hashedit", ".", "grid", "[", "x", "]", ".", "desc", "+", "'</small>'", ";", "list", ".", "appendChild", "(", "el", ")", ";", "}", "list", ".", "addEventListener", "(", "'click'", ",", "function", "(", "e", ")", "{", "target", "=", "e", ".", "target", ";", "if", "(", "target", ".", "nodeName", ".", "toUpperCase", "(", ")", "!==", "'DIV'", ")", "{", "target", "=", "hashedit", ".", "findParentBySelector", "(", "target", ",", "'.hashedit-list-item'", ")", ";", "}", "if", "(", "target", "!=", "null", ")", "{", "i", "=", "target", ".", "getAttribute", "(", "'data-index'", ")", ";", "html", "=", "hashedit", ".", "grid", "[", "i", "]", ".", "html", ";", "hashedit", ".", "appendBlock", "(", "html", ",", "block", ",", "'before'", ")", ";", "hashedit", ".", "setupBlocks", "(", ")", ";", "dialog", ".", "removeAttribute", "(", "'visible'", ")", ";", "}", "}", ")", ";", "}", "dialog", ".", "setAttribute", "(", "'visible'", ",", "''", ")", ";", "}" ]
Sets up the layout dialog
[ "Sets", "up", "the", "layout", "dialog" ]
14b5570cc7a97f8bdcfa596ce27260d25f8e18da
https://github.com/madoublet/hashedit/blob/14b5570cc7a97f8bdcfa596ce27260d25f8e18da/dist/hashedit.js#L2225-L2281
train
madoublet/hashedit
dist/hashedit.js
function() { var id, cssClass, src, target, link, alt, title; // populate link values if (hashedit.current.node !== null) { // get attributes id = hashedit.current.node.getAttribute('id') || ''; cssClass = hashedit.current.node.getAttribute('class') || ''; src = hashedit.current.node.getAttribute('src') || ''; alt = hashedit.current.node.getAttribute('alt') || ''; title = hashedit.current.node.getAttribute('title') || ''; // show the link dialog link = document.querySelector('#hashedit-image-settings-modal'); link.setAttribute('visible', ''); // sets start values document.getElementById('hashedit-image-id').value = id; document.getElementById('hashedit-image-cssclass').value = cssClass; document.getElementById('hashedit-image-src').value = src; document.getElementById('hashedit-image-alt').value = alt; document.getElementById('hashedit-image-title').value = title; } }
javascript
function() { var id, cssClass, src, target, link, alt, title; // populate link values if (hashedit.current.node !== null) { // get attributes id = hashedit.current.node.getAttribute('id') || ''; cssClass = hashedit.current.node.getAttribute('class') || ''; src = hashedit.current.node.getAttribute('src') || ''; alt = hashedit.current.node.getAttribute('alt') || ''; title = hashedit.current.node.getAttribute('title') || ''; // show the link dialog link = document.querySelector('#hashedit-image-settings-modal'); link.setAttribute('visible', ''); // sets start values document.getElementById('hashedit-image-id').value = id; document.getElementById('hashedit-image-cssclass').value = cssClass; document.getElementById('hashedit-image-src').value = src; document.getElementById('hashedit-image-alt').value = alt; document.getElementById('hashedit-image-title').value = title; } }
[ "function", "(", ")", "{", "var", "id", ",", "cssClass", ",", "src", ",", "target", ",", "link", ",", "alt", ",", "title", ";", "if", "(", "hashedit", ".", "current", ".", "node", "!==", "null", ")", "{", "id", "=", "hashedit", ".", "current", ".", "node", ".", "getAttribute", "(", "'id'", ")", "||", "''", ";", "cssClass", "=", "hashedit", ".", "current", ".", "node", ".", "getAttribute", "(", "'class'", ")", "||", "''", ";", "src", "=", "hashedit", ".", "current", ".", "node", ".", "getAttribute", "(", "'src'", ")", "||", "''", ";", "alt", "=", "hashedit", ".", "current", ".", "node", ".", "getAttribute", "(", "'alt'", ")", "||", "''", ";", "title", "=", "hashedit", ".", "current", ".", "node", ".", "getAttribute", "(", "'title'", ")", "||", "''", ";", "link", "=", "document", ".", "querySelector", "(", "'#hashedit-image-settings-modal'", ")", ";", "link", ".", "setAttribute", "(", "'visible'", ",", "''", ")", ";", "document", ".", "getElementById", "(", "'hashedit-image-id'", ")", ".", "value", "=", "id", ";", "document", ".", "getElementById", "(", "'hashedit-image-cssclass'", ")", ".", "value", "=", "cssClass", ";", "document", ".", "getElementById", "(", "'hashedit-image-src'", ")", ".", "value", "=", "src", ";", "document", ".", "getElementById", "(", "'hashedit-image-alt'", ")", ".", "value", "=", "alt", ";", "document", ".", "getElementById", "(", "'hashedit-image-title'", ")", ".", "value", "=", "title", ";", "}", "}" ]
Sets up the images dialog
[ "Sets", "up", "the", "images", "dialog" ]
14b5570cc7a97f8bdcfa596ce27260d25f8e18da
https://github.com/madoublet/hashedit/blob/14b5570cc7a97f8bdcfa596ce27260d25f8e18da/dist/hashedit.js#L2286-L2314
train
madoublet/hashedit
dist/hashedit.js
function() { var ranges, i, sel, len; if (window.getSelection) { sel = window.getSelection(); if (sel.getRangeAt && sel.rangeCount) { ranges = []; len = sel.rangeCount; for (i = 0; i < len; i += 1) { ranges.push(sel.getRangeAt(i)); } return ranges; } } else if (document.selection && document.selection.createRange) { return document.selection.createRange(); } return null; }
javascript
function() { var ranges, i, sel, len; if (window.getSelection) { sel = window.getSelection(); if (sel.getRangeAt && sel.rangeCount) { ranges = []; len = sel.rangeCount; for (i = 0; i < len; i += 1) { ranges.push(sel.getRangeAt(i)); } return ranges; } } else if (document.selection && document.selection.createRange) { return document.selection.createRange(); } return null; }
[ "function", "(", ")", "{", "var", "ranges", ",", "i", ",", "sel", ",", "len", ";", "if", "(", "window", ".", "getSelection", ")", "{", "sel", "=", "window", ".", "getSelection", "(", ")", ";", "if", "(", "sel", ".", "getRangeAt", "&&", "sel", ".", "rangeCount", ")", "{", "ranges", "=", "[", "]", ";", "len", "=", "sel", ".", "rangeCount", ";", "for", "(", "i", "=", "0", ";", "i", "<", "len", ";", "i", "+=", "1", ")", "{", "ranges", ".", "push", "(", "sel", ".", "getRangeAt", "(", "i", ")", ")", ";", "}", "return", "ranges", ";", "}", "}", "else", "if", "(", "document", ".", "selection", "&&", "document", ".", "selection", ".", "createRange", ")", "{", "return", "document", ".", "selection", ".", "createRange", "(", ")", ";", "}", "return", "null", ";", "}" ]
Saves text selection
[ "Saves", "text", "selection" ]
14b5570cc7a97f8bdcfa596ce27260d25f8e18da
https://github.com/madoublet/hashedit/blob/14b5570cc7a97f8bdcfa596ce27260d25f8e18da/dist/hashedit.js#L2355-L2373
train
madoublet/hashedit
dist/hashedit.js
function() { var parent, selection, range, div, links; parent = null; if (document.selection) { parent = document.selection.createRange().parentElement(); } else { selection = window.getSelection(); if (selection.rangeCount > 0) { parent = selection.getRangeAt(0).startContainer.parentNode; } } if (parent !== null) { if (parent.tagName == 'A') { return parent; } } if (window.getSelection) { selection = window.getSelection(); if (selection.rangeCount > 0) { range = selection.getRangeAt(0); div = document.createElement('DIV'); div.appendChild(range.cloneContents()); links = div.getElementsByTagName("A"); if (links.length > 0) { return links[0]; } else { return null; } } } return null; }
javascript
function() { var parent, selection, range, div, links; parent = null; if (document.selection) { parent = document.selection.createRange().parentElement(); } else { selection = window.getSelection(); if (selection.rangeCount > 0) { parent = selection.getRangeAt(0).startContainer.parentNode; } } if (parent !== null) { if (parent.tagName == 'A') { return parent; } } if (window.getSelection) { selection = window.getSelection(); if (selection.rangeCount > 0) { range = selection.getRangeAt(0); div = document.createElement('DIV'); div.appendChild(range.cloneContents()); links = div.getElementsByTagName("A"); if (links.length > 0) { return links[0]; } else { return null; } } } return null; }
[ "function", "(", ")", "{", "var", "parent", ",", "selection", ",", "range", ",", "div", ",", "links", ";", "parent", "=", "null", ";", "if", "(", "document", ".", "selection", ")", "{", "parent", "=", "document", ".", "selection", ".", "createRange", "(", ")", ".", "parentElement", "(", ")", ";", "}", "else", "{", "selection", "=", "window", ".", "getSelection", "(", ")", ";", "if", "(", "selection", ".", "rangeCount", ">", "0", ")", "{", "parent", "=", "selection", ".", "getRangeAt", "(", "0", ")", ".", "startContainer", ".", "parentNode", ";", "}", "}", "if", "(", "parent", "!==", "null", ")", "{", "if", "(", "parent", ".", "tagName", "==", "'A'", ")", "{", "return", "parent", ";", "}", "}", "if", "(", "window", ".", "getSelection", ")", "{", "selection", "=", "window", ".", "getSelection", "(", ")", ";", "if", "(", "selection", ".", "rangeCount", ">", "0", ")", "{", "range", "=", "selection", ".", "getRangeAt", "(", "0", ")", ";", "div", "=", "document", ".", "createElement", "(", "'DIV'", ")", ";", "div", ".", "appendChild", "(", "range", ".", "cloneContents", "(", ")", ")", ";", "links", "=", "div", ".", "getElementsByTagName", "(", "\"A\"", ")", ";", "if", "(", "links", ".", "length", ">", "0", ")", "{", "return", "links", "[", "0", "]", ";", "}", "else", "{", "return", "null", ";", "}", "}", "}", "return", "null", ";", "}" ]
Retrieve a link from the selection
[ "Retrieve", "a", "link", "from", "the", "selection" ]
14b5570cc7a97f8bdcfa596ce27260d25f8e18da
https://github.com/madoublet/hashedit/blob/14b5570cc7a97f8bdcfa596ce27260d25f8e18da/dist/hashedit.js#L2378-L2418
train
madoublet/hashedit
dist/hashedit.js
function(node) { var style, textColor, textSize, textShadowColor, textShadowHorizontal, textShadowVertical, textShadowBlur; // get current node style = ''; // build a style attribute for (text-color, text-size, text-shadow-color, text-shadow-vertical, text-shadow-horizontal, text-shadow-blur) textColor = node.getAttribute('text-color') || ''; textSize = node.getAttribute('text-size') || ''; textShadowColor = node.getAttribute('text-shadow-color') || ''; textShadowHorizontal = node.getAttribute('text-shadow-horizontal') || ''; textShadowVertical = node.getAttribute('text-shadow-horizontal') || ''; textShadowBlur = node.getAttribute('text-shadow-blur') || ''; if (textColor !== '') { style += 'color:' + textColor + ';'; } if (textSize !== '') { style += 'font-size:' + textSize + ';'; } if (textShadowColor !== '') { style += 'text-shadow: ' + textShadowHorizontal + ' ' + textShadowVertical + ' ' + textShadowBlur + ' ' + textShadowColor + ';'; } return style; }
javascript
function(node) { var style, textColor, textSize, textShadowColor, textShadowHorizontal, textShadowVertical, textShadowBlur; // get current node style = ''; // build a style attribute for (text-color, text-size, text-shadow-color, text-shadow-vertical, text-shadow-horizontal, text-shadow-blur) textColor = node.getAttribute('text-color') || ''; textSize = node.getAttribute('text-size') || ''; textShadowColor = node.getAttribute('text-shadow-color') || ''; textShadowHorizontal = node.getAttribute('text-shadow-horizontal') || ''; textShadowVertical = node.getAttribute('text-shadow-horizontal') || ''; textShadowBlur = node.getAttribute('text-shadow-blur') || ''; if (textColor !== '') { style += 'color:' + textColor + ';'; } if (textSize !== '') { style += 'font-size:' + textSize + ';'; } if (textShadowColor !== '') { style += 'text-shadow: ' + textShadowHorizontal + ' ' + textShadowVertical + ' ' + textShadowBlur + ' ' + textShadowColor + ';'; } return style; }
[ "function", "(", "node", ")", "{", "var", "style", ",", "textColor", ",", "textSize", ",", "textShadowColor", ",", "textShadowHorizontal", ",", "textShadowVertical", ",", "textShadowBlur", ";", "style", "=", "''", ";", "textColor", "=", "node", ".", "getAttribute", "(", "'text-color'", ")", "||", "''", ";", "textSize", "=", "node", ".", "getAttribute", "(", "'text-size'", ")", "||", "''", ";", "textShadowColor", "=", "node", ".", "getAttribute", "(", "'text-shadow-color'", ")", "||", "''", ";", "textShadowHorizontal", "=", "node", ".", "getAttribute", "(", "'text-shadow-horizontal'", ")", "||", "''", ";", "textShadowVertical", "=", "node", ".", "getAttribute", "(", "'text-shadow-horizontal'", ")", "||", "''", ";", "textShadowBlur", "=", "node", ".", "getAttribute", "(", "'text-shadow-blur'", ")", "||", "''", ";", "if", "(", "textColor", "!==", "''", ")", "{", "style", "+=", "'color:'", "+", "textColor", "+", "';'", ";", "}", "if", "(", "textSize", "!==", "''", ")", "{", "style", "+=", "'font-size:'", "+", "textSize", "+", "';'", ";", "}", "if", "(", "textShadowColor", "!==", "''", ")", "{", "style", "+=", "'text-shadow: '", "+", "textShadowHorizontal", "+", "' '", "+", "textShadowVertical", "+", "' '", "+", "textShadowBlur", "+", "' '", "+", "textShadowColor", "+", "';'", ";", "}", "return", "style", ";", "}" ]
Executes a function by its name and applies arguments @param {HTMLElement} node
[ "Executes", "a", "function", "by", "its", "name", "and", "applies", "arguments" ]
14b5570cc7a97f8bdcfa596ce27260d25f8e18da
https://github.com/madoublet/hashedit/blob/14b5570cc7a97f8bdcfa596ce27260d25f8e18da/dist/hashedit.js#L2445-L2476
train
madoublet/hashedit
dist/hashedit.js
function() { var toast; toast = document.createElement('div'); toast.setAttribute('class', 'hashedit-toast'); toast.innerHTML = 'Sample Toast'; // append toast if (hashedit.current) { hashedit.current.container.appendChild(toast); } else { document.body.appendChild(toast); } }
javascript
function() { var toast; toast = document.createElement('div'); toast.setAttribute('class', 'hashedit-toast'); toast.innerHTML = 'Sample Toast'; // append toast if (hashedit.current) { hashedit.current.container.appendChild(toast); } else { document.body.appendChild(toast); } }
[ "function", "(", ")", "{", "var", "toast", ";", "toast", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "toast", ".", "setAttribute", "(", "'class'", ",", "'hashedit-toast'", ")", ";", "toast", ".", "innerHTML", "=", "'Sample Toast'", ";", "if", "(", "hashedit", ".", "current", ")", "{", "hashedit", ".", "current", ".", "container", ".", "appendChild", "(", "toast", ")", ";", "}", "else", "{", "document", ".", "body", ".", "appendChild", "(", "toast", ")", ";", "}", "}" ]
Create the toast
[ "Create", "the", "toast" ]
14b5570cc7a97f8bdcfa596ce27260d25f8e18da
https://github.com/madoublet/hashedit/blob/14b5570cc7a97f8bdcfa596ce27260d25f8e18da/dist/hashedit.js#L2979-L2994
train
madoublet/hashedit
dist/hashedit.js
function(src, stringToFind, stringToReplace) { var temp, index; temp = src; index = temp.indexOf(stringToFind); while (index != -1) { temp = temp.replace(stringToFind, stringToReplace); index = temp.indexOf(stringToFind); } return temp; }
javascript
function(src, stringToFind, stringToReplace) { var temp, index; temp = src; index = temp.indexOf(stringToFind); while (index != -1) { temp = temp.replace(stringToFind, stringToReplace); index = temp.indexOf(stringToFind); } return temp; }
[ "function", "(", "src", ",", "stringToFind", ",", "stringToReplace", ")", "{", "var", "temp", ",", "index", ";", "temp", "=", "src", ";", "index", "=", "temp", ".", "indexOf", "(", "stringToFind", ")", ";", "while", "(", "index", "!=", "-", "1", ")", "{", "temp", "=", "temp", ".", "replace", "(", "stringToFind", ",", "stringToReplace", ")", ";", "index", "=", "temp", ".", "indexOf", "(", "stringToFind", ")", ";", "}", "return", "temp", ";", "}" ]
Replace all occurrences of a string @param {String} src - Source string (e.g. haystack) @param {String} stringToFind - String to find (e.g. needle) @param {String} stringToReplace - String to replacr
[ "Replace", "all", "occurrences", "of", "a", "string" ]
14b5570cc7a97f8bdcfa596ce27260d25f8e18da
https://github.com/madoublet/hashedit/blob/14b5570cc7a97f8bdcfa596ce27260d25f8e18da/dist/hashedit.js#L3002-L3015
train
madoublet/hashedit
dist/hashedit.js
function(language){ var els, x, id, html; // select elements els = document.querySelectorAll('[data-i18n]'); // walk through elements for(x=0; x<els.length; x++){ id = els[x].getAttribute('data-i18n'); // set id to text if empty if(id == ''){ id = els[x].innerText(); } // translate html = hashedit.i18n(id); els[x].innerHTML = html; } }
javascript
function(language){ var els, x, id, html; // select elements els = document.querySelectorAll('[data-i18n]'); // walk through elements for(x=0; x<els.length; x++){ id = els[x].getAttribute('data-i18n'); // set id to text if empty if(id == ''){ id = els[x].innerText(); } // translate html = hashedit.i18n(id); els[x].innerHTML = html; } }
[ "function", "(", "language", ")", "{", "var", "els", ",", "x", ",", "id", ",", "html", ";", "els", "=", "document", ".", "querySelectorAll", "(", "'[data-i18n]'", ")", ";", "for", "(", "x", "=", "0", ";", "x", "<", "els", ".", "length", ";", "x", "++", ")", "{", "id", "=", "els", "[", "x", "]", ".", "getAttribute", "(", "'data-i18n'", ")", ";", "if", "(", "id", "==", "''", ")", "{", "id", "=", "els", "[", "x", "]", ".", "innerText", "(", ")", ";", "}", "html", "=", "hashedit", ".", "i18n", "(", "id", ")", ";", "els", "[", "x", "]", ".", "innerHTML", "=", "html", ";", "}", "}" ]
translates a page
[ "translates", "a", "page" ]
14b5570cc7a97f8bdcfa596ce27260d25f8e18da
https://github.com/madoublet/hashedit/blob/14b5570cc7a97f8bdcfa596ce27260d25f8e18da/dist/hashedit.js#L3051-L3073
train
madoublet/hashedit
dist/hashedit.js
function(text){ var options, language, path; language = hashedit.language; // translatable if(hashedit.canTranslate === true) { // make sure library is installed if(i18n !== undefined) { if(hashedit.isI18nInit === false) { // get language path path = hashedit.languagePath; path = hashedit.replaceAll(path, '{{language}}', hashedit.language); // set language options = { lng: hashedit.language, getAsync : false, useCookie: false, useLocalStorage: false, fallbackLng: 'en', resGetPath: path, defaultLoadingValue: '' }; // init i18n.init(options); // set flag hashedit.isI18nInit = true; } } } return i18n.t(text); }
javascript
function(text){ var options, language, path; language = hashedit.language; // translatable if(hashedit.canTranslate === true) { // make sure library is installed if(i18n !== undefined) { if(hashedit.isI18nInit === false) { // get language path path = hashedit.languagePath; path = hashedit.replaceAll(path, '{{language}}', hashedit.language); // set language options = { lng: hashedit.language, getAsync : false, useCookie: false, useLocalStorage: false, fallbackLng: 'en', resGetPath: path, defaultLoadingValue: '' }; // init i18n.init(options); // set flag hashedit.isI18nInit = true; } } } return i18n.t(text); }
[ "function", "(", "text", ")", "{", "var", "options", ",", "language", ",", "path", ";", "language", "=", "hashedit", ".", "language", ";", "if", "(", "hashedit", ".", "canTranslate", "===", "true", ")", "{", "if", "(", "i18n", "!==", "undefined", ")", "{", "if", "(", "hashedit", ".", "isI18nInit", "===", "false", ")", "{", "path", "=", "hashedit", ".", "languagePath", ";", "path", "=", "hashedit", ".", "replaceAll", "(", "path", ",", "'{{language}}'", ",", "hashedit", ".", "language", ")", ";", "options", "=", "{", "lng", ":", "hashedit", ".", "language", ",", "getAsync", ":", "false", ",", "useCookie", ":", "false", ",", "useLocalStorage", ":", "false", ",", "fallbackLng", ":", "'en'", ",", "resGetPath", ":", "path", ",", "defaultLoadingValue", ":", "''", "}", ";", "i18n", ".", "init", "(", "options", ")", ";", "hashedit", ".", "isI18nInit", "=", "true", ";", "}", "}", "}", "return", "i18n", ".", "t", "(", "text", ")", ";", "}" ]
translates a text string
[ "translates", "a", "text", "string" ]
14b5570cc7a97f8bdcfa596ce27260d25f8e18da
https://github.com/madoublet/hashedit/blob/14b5570cc7a97f8bdcfa596ce27260d25f8e18da/dist/hashedit.js#L3076-L3116
train
RetailMeNotSandbox/roux
index.js
initAndCachePantry
function initAndCachePantry(pantryCache, config) { return initialize(config) .then(function (initializedPantry) { // cache the pantry for next time pantryCache[config.name] = initializedPantry; return initializedPantry; }); }
javascript
function initAndCachePantry(pantryCache, config) { return initialize(config) .then(function (initializedPantry) { // cache the pantry for next time pantryCache[config.name] = initializedPantry; return initializedPantry; }); }
[ "function", "initAndCachePantry", "(", "pantryCache", ",", "config", ")", "{", "return", "initialize", "(", "config", ")", ".", "then", "(", "function", "(", "initializedPantry", ")", "{", "pantryCache", "[", "config", ".", "name", "]", "=", "initializedPantry", ";", "return", "initializedPantry", ";", "}", ")", ";", "}" ]
Proxies to initialize but adds the result to the pantryCache before returning it. @param {Object} pantryCache cache of pantry objects. The result of initialize will be stored in pantryCache[config.name] @param {Object} config config to be passed to initialize @return {Promise} promise for the initialized pantry. Once resolved pantryCache will contain the initialized pantry.
[ "Proxies", "to", "initialize", "but", "adds", "the", "result", "to", "the", "pantryCache", "before", "returning", "it", "." ]
519616c4deeb47545da44098767e71dfd10a0e83
https://github.com/RetailMeNotSandbox/roux/blob/519616c4deeb47545da44098767e71dfd10a0e83/index.js#L457-L464
train
RetailMeNotSandbox/roux
index.js
normalizeConfig
function normalizeConfig(config, defaults) { if (_.isUndefined(config)) { config = {}; } if (!_.isObject(config)) { throw new TypeError('`config` must be an object'); } if (_.isUndefined(defaults)) { defaults = {}; } if (!_.isObject(defaults)) { throw new TypeError('`defaults` must be an object'); } config = _.defaults({}, config, defaults, { pantries: {}, pantrySearchPaths: [path.resolve('node_modules')] }); if (!_.isObject(config.pantries)) { throw new TypeError('`config.pantries` must be an object'); } if (!_.isArray(config.pantrySearchPaths)) { throw new TypeError('`config.pantrySearchPaths` must be an Array'); } return config; }
javascript
function normalizeConfig(config, defaults) { if (_.isUndefined(config)) { config = {}; } if (!_.isObject(config)) { throw new TypeError('`config` must be an object'); } if (_.isUndefined(defaults)) { defaults = {}; } if (!_.isObject(defaults)) { throw new TypeError('`defaults` must be an object'); } config = _.defaults({}, config, defaults, { pantries: {}, pantrySearchPaths: [path.resolve('node_modules')] }); if (!_.isObject(config.pantries)) { throw new TypeError('`config.pantries` must be an object'); } if (!_.isArray(config.pantrySearchPaths)) { throw new TypeError('`config.pantrySearchPaths` must be an Array'); } return config; }
[ "function", "normalizeConfig", "(", "config", ",", "defaults", ")", "{", "if", "(", "_", ".", "isUndefined", "(", "config", ")", ")", "{", "config", "=", "{", "}", ";", "}", "if", "(", "!", "_", ".", "isObject", "(", "config", ")", ")", "{", "throw", "new", "TypeError", "(", "'`config` must be an object'", ")", ";", "}", "if", "(", "_", ".", "isUndefined", "(", "defaults", ")", ")", "{", "defaults", "=", "{", "}", ";", "}", "if", "(", "!", "_", ".", "isObject", "(", "defaults", ")", ")", "{", "throw", "new", "TypeError", "(", "'`defaults` must be an object'", ")", ";", "}", "config", "=", "_", ".", "defaults", "(", "{", "}", ",", "config", ",", "defaults", ",", "{", "pantries", ":", "{", "}", ",", "pantrySearchPaths", ":", "[", "path", ".", "resolve", "(", "'node_modules'", ")", "]", "}", ")", ";", "if", "(", "!", "_", ".", "isObject", "(", "config", ".", "pantries", ")", ")", "{", "throw", "new", "TypeError", "(", "'`config.pantries` must be an object'", ")", ";", "}", "if", "(", "!", "_", ".", "isArray", "(", "config", ".", "pantrySearchPaths", ")", ")", "{", "throw", "new", "TypeError", "(", "'`config.pantrySearchPaths` must be an Array'", ")", ";", "}", "return", "config", ";", "}" ]
Normalize an config common to a Roux pantry Some modules, such as roux-sass-importer may want to expose a similar api to resolve. This method validates and initializes the configuration accepted by the resolve method. @param {Object} [config] - configuration object @param {Object} config.pantries - a cache of `Pantry` instances @param {string[]} config.pantrySearchPaths - the paths to search for pantries @param {Object} defaults defaults to use when initializing the config @return {Object} valid and initialized config
[ "Normalize", "an", "config", "common", "to", "a", "Roux", "pantry" ]
519616c4deeb47545da44098767e71dfd10a0e83
https://github.com/RetailMeNotSandbox/roux/blob/519616c4deeb47545da44098767e71dfd10a0e83/index.js#L480-L511
train
bholloway/persistent-cache-webpack-plugin
index.js
onInit
function onInit(unused, callback) { var filePath = path.resolve(options.file); stats.deserialise.fs.start = Date.now(); if (fs.existsSync(filePath)) { fs.readFile(filePath, complete); } else { complete(true); } function complete(error, contents) { stats.deserialise.fs.stop = Date.now(); stats.deserialise.decode.start = Date.now(); pending = !error && contents && cycle.retrocycle(decode(JSON.parse(contents))); stats.deserialise.decode.stop = Date.now(); stats.deserialise.success = !error; callback(); } }
javascript
function onInit(unused, callback) { var filePath = path.resolve(options.file); stats.deserialise.fs.start = Date.now(); if (fs.existsSync(filePath)) { fs.readFile(filePath, complete); } else { complete(true); } function complete(error, contents) { stats.deserialise.fs.stop = Date.now(); stats.deserialise.decode.start = Date.now(); pending = !error && contents && cycle.retrocycle(decode(JSON.parse(contents))); stats.deserialise.decode.stop = Date.now(); stats.deserialise.success = !error; callback(); } }
[ "function", "onInit", "(", "unused", ",", "callback", ")", "{", "var", "filePath", "=", "path", ".", "resolve", "(", "options", ".", "file", ")", ";", "stats", ".", "deserialise", ".", "fs", ".", "start", "=", "Date", ".", "now", "(", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "filePath", ")", ")", "{", "fs", ".", "readFile", "(", "filePath", ",", "complete", ")", ";", "}", "else", "{", "complete", "(", "true", ")", ";", "}", "function", "complete", "(", "error", ",", "contents", ")", "{", "stats", ".", "deserialise", ".", "fs", ".", "stop", "=", "Date", ".", "now", "(", ")", ";", "stats", ".", "deserialise", ".", "decode", ".", "start", "=", "Date", ".", "now", "(", ")", ";", "pending", "=", "!", "error", "&&", "contents", "&&", "cycle", ".", "retrocycle", "(", "decode", "(", "JSON", ".", "parse", "(", "contents", ")", ")", ")", ";", "stats", ".", "deserialise", ".", "decode", ".", "stop", "=", "Date", ".", "now", "(", ")", ";", "stats", ".", "deserialise", ".", "success", "=", "!", "error", ";", "callback", "(", ")", ";", "}", "}" ]
Deserialise any existing file into pending cache elements.
[ "Deserialise", "any", "existing", "file", "into", "pending", "cache", "elements", "." ]
bd5aec58b1b38477218dcdc0fb144c6981604fa8
https://github.com/bholloway/persistent-cache-webpack-plugin/blob/bd5aec58b1b38477218dcdc0fb144c6981604fa8/index.js#L49-L69
train
bholloway/persistent-cache-webpack-plugin
index.js
afterEmit
function afterEmit(compilation, callback) { var failures; if (options.persist) { var cache = compilation.cache, filePath = path.resolve(options.file); stats.serialise.encode.start = Date.now(); var encoded = encode(cache); failures = (encoded.$failed || []) .filter(filterIgnored); delete encoded.$failed; stats.serialise.encode.stop = Date.now(); stats.failures = failures.length; // abort if (failures.length) { stats.serialise.fs.start = Date.now(); fs.unlink(filePath, complete.bind(null, true)); } // serialise and write file else { stats.serialise.decycle.start = Date.now(); var decycled = cycle.decycle(encoded); stats.serialise.decycle.stop = Date.now(); stats.serialise.fs.start = Date.now(); var buffer = new Buffer(JSON.stringify(decycled, null, 2)); stats.serialise.size = buffer.length; fs.writeFile(filePath, buffer, complete); } } else { failures = []; complete(); } function complete(error) { stats.serialise.fs.stop = Date.now(); stats.serialise.success = !error; options.warn && pushFailures(failures, compilation.warnings, (options.warn === 'verbose')); options.stats && printStats(stats); callback(); } }
javascript
function afterEmit(compilation, callback) { var failures; if (options.persist) { var cache = compilation.cache, filePath = path.resolve(options.file); stats.serialise.encode.start = Date.now(); var encoded = encode(cache); failures = (encoded.$failed || []) .filter(filterIgnored); delete encoded.$failed; stats.serialise.encode.stop = Date.now(); stats.failures = failures.length; // abort if (failures.length) { stats.serialise.fs.start = Date.now(); fs.unlink(filePath, complete.bind(null, true)); } // serialise and write file else { stats.serialise.decycle.start = Date.now(); var decycled = cycle.decycle(encoded); stats.serialise.decycle.stop = Date.now(); stats.serialise.fs.start = Date.now(); var buffer = new Buffer(JSON.stringify(decycled, null, 2)); stats.serialise.size = buffer.length; fs.writeFile(filePath, buffer, complete); } } else { failures = []; complete(); } function complete(error) { stats.serialise.fs.stop = Date.now(); stats.serialise.success = !error; options.warn && pushFailures(failures, compilation.warnings, (options.warn === 'verbose')); options.stats && printStats(stats); callback(); } }
[ "function", "afterEmit", "(", "compilation", ",", "callback", ")", "{", "var", "failures", ";", "if", "(", "options", ".", "persist", ")", "{", "var", "cache", "=", "compilation", ".", "cache", ",", "filePath", "=", "path", ".", "resolve", "(", "options", ".", "file", ")", ";", "stats", ".", "serialise", ".", "encode", ".", "start", "=", "Date", ".", "now", "(", ")", ";", "var", "encoded", "=", "encode", "(", "cache", ")", ";", "failures", "=", "(", "encoded", ".", "$failed", "||", "[", "]", ")", ".", "filter", "(", "filterIgnored", ")", ";", "delete", "encoded", ".", "$failed", ";", "stats", ".", "serialise", ".", "encode", ".", "stop", "=", "Date", ".", "now", "(", ")", ";", "stats", ".", "failures", "=", "failures", ".", "length", ";", "if", "(", "failures", ".", "length", ")", "{", "stats", ".", "serialise", ".", "fs", ".", "start", "=", "Date", ".", "now", "(", ")", ";", "fs", ".", "unlink", "(", "filePath", ",", "complete", ".", "bind", "(", "null", ",", "true", ")", ")", ";", "}", "else", "{", "stats", ".", "serialise", ".", "decycle", ".", "start", "=", "Date", ".", "now", "(", ")", ";", "var", "decycled", "=", "cycle", ".", "decycle", "(", "encoded", ")", ";", "stats", ".", "serialise", ".", "decycle", ".", "stop", "=", "Date", ".", "now", "(", ")", ";", "stats", ".", "serialise", ".", "fs", ".", "start", "=", "Date", ".", "now", "(", ")", ";", "var", "buffer", "=", "new", "Buffer", "(", "JSON", ".", "stringify", "(", "decycled", ",", "null", ",", "2", ")", ")", ";", "stats", ".", "serialise", ".", "size", "=", "buffer", ".", "length", ";", "fs", ".", "writeFile", "(", "filePath", ",", "buffer", ",", "complete", ")", ";", "}", "}", "else", "{", "failures", "=", "[", "]", ";", "complete", "(", ")", ";", "}", "function", "complete", "(", "error", ")", "{", "stats", ".", "serialise", ".", "fs", ".", "stop", "=", "Date", ".", "now", "(", ")", ";", "stats", ".", "serialise", ".", "success", "=", "!", "error", ";", "options", ".", "warn", "&&", "pushFailures", "(", "failures", ",", "compilation", ".", "warnings", ",", "(", "options", ".", "warn", "===", "'verbose'", ")", ")", ";", "options", ".", "stats", "&&", "printStats", "(", "stats", ")", ";", "callback", "(", ")", ";", "}", "}" ]
Serialise the cache to file, don't wait for async.
[ "Serialise", "the", "cache", "to", "file", "don", "t", "wait", "for", "async", "." ]
bd5aec58b1b38477218dcdc0fb144c6981604fa8
https://github.com/bholloway/persistent-cache-webpack-plugin/blob/bd5aec58b1b38477218dcdc0fb144c6981604fa8/index.js#L81-L125
train
jhermsmeier/node-udif
lib/blockmap.js
function( buffer, offset ) { offset = offset || 0 this.signature = buffer.readUInt32BE( offset + 0 ) if( this.signature !== BlockMap.signature ) { var expected = BlockMap.signature.toString(16) var actual = this.signature.toString(16) throw new Error( `Invalid block map signature: Expected 0x${expected}, saw 0x${actual}` ) } this.version = buffer.readUInt32BE( offset + 4 ) this.sectorNumber = uint64.readBE( buffer, offset + 8, 8 ) this.sectorCount = uint64.readBE( buffer, offset + 16, 8 ) this.dataOffset = uint64.readBE( buffer, offset + 24, 8 ) this.buffersNeeded = buffer.readUInt32BE( offset + 32 ) this.blockDescriptorCount = buffer.readUInt32BE( offset + 36 ) this.reserved1 = buffer.readUInt32BE( offset + 40 ) this.reserved2 = buffer.readUInt32BE( offset + 44 ) this.reserved3 = buffer.readUInt32BE( offset + 48 ) this.reserved4 = buffer.readUInt32BE( offset + 52 ) this.reserved5 = buffer.readUInt32BE( offset + 56 ) this.reserved6 = buffer.readUInt32BE( offset + 60 ) this.checksum.parse( buffer, offset + 64 ) this.blockCount = buffer.readUInt32BE( offset + 200 ) this.blocks = [] for( var i = 0; i < this.blockCount; i++ ) { this.blocks.push( BlockMap.Block.parse( buffer, offset + 204 + ( i * 40 ) ) ) } return this }
javascript
function( buffer, offset ) { offset = offset || 0 this.signature = buffer.readUInt32BE( offset + 0 ) if( this.signature !== BlockMap.signature ) { var expected = BlockMap.signature.toString(16) var actual = this.signature.toString(16) throw new Error( `Invalid block map signature: Expected 0x${expected}, saw 0x${actual}` ) } this.version = buffer.readUInt32BE( offset + 4 ) this.sectorNumber = uint64.readBE( buffer, offset + 8, 8 ) this.sectorCount = uint64.readBE( buffer, offset + 16, 8 ) this.dataOffset = uint64.readBE( buffer, offset + 24, 8 ) this.buffersNeeded = buffer.readUInt32BE( offset + 32 ) this.blockDescriptorCount = buffer.readUInt32BE( offset + 36 ) this.reserved1 = buffer.readUInt32BE( offset + 40 ) this.reserved2 = buffer.readUInt32BE( offset + 44 ) this.reserved3 = buffer.readUInt32BE( offset + 48 ) this.reserved4 = buffer.readUInt32BE( offset + 52 ) this.reserved5 = buffer.readUInt32BE( offset + 56 ) this.reserved6 = buffer.readUInt32BE( offset + 60 ) this.checksum.parse( buffer, offset + 64 ) this.blockCount = buffer.readUInt32BE( offset + 200 ) this.blocks = [] for( var i = 0; i < this.blockCount; i++ ) { this.blocks.push( BlockMap.Block.parse( buffer, offset + 204 + ( i * 40 ) ) ) } return this }
[ "function", "(", "buffer", ",", "offset", ")", "{", "offset", "=", "offset", "||", "0", "this", ".", "signature", "=", "buffer", ".", "readUInt32BE", "(", "offset", "+", "0", ")", "if", "(", "this", ".", "signature", "!==", "BlockMap", ".", "signature", ")", "{", "var", "expected", "=", "BlockMap", ".", "signature", ".", "toString", "(", "16", ")", "var", "actual", "=", "this", ".", "signature", ".", "toString", "(", "16", ")", "throw", "new", "Error", "(", "`", "${", "expected", "}", "${", "actual", "}", "`", ")", "}", "this", ".", "version", "=", "buffer", ".", "readUInt32BE", "(", "offset", "+", "4", ")", "this", ".", "sectorNumber", "=", "uint64", ".", "readBE", "(", "buffer", ",", "offset", "+", "8", ",", "8", ")", "this", ".", "sectorCount", "=", "uint64", ".", "readBE", "(", "buffer", ",", "offset", "+", "16", ",", "8", ")", "this", ".", "dataOffset", "=", "uint64", ".", "readBE", "(", "buffer", ",", "offset", "+", "24", ",", "8", ")", "this", ".", "buffersNeeded", "=", "buffer", ".", "readUInt32BE", "(", "offset", "+", "32", ")", "this", ".", "blockDescriptorCount", "=", "buffer", ".", "readUInt32BE", "(", "offset", "+", "36", ")", "this", ".", "reserved1", "=", "buffer", ".", "readUInt32BE", "(", "offset", "+", "40", ")", "this", ".", "reserved2", "=", "buffer", ".", "readUInt32BE", "(", "offset", "+", "44", ")", "this", ".", "reserved3", "=", "buffer", ".", "readUInt32BE", "(", "offset", "+", "48", ")", "this", ".", "reserved4", "=", "buffer", ".", "readUInt32BE", "(", "offset", "+", "52", ")", "this", ".", "reserved5", "=", "buffer", ".", "readUInt32BE", "(", "offset", "+", "56", ")", "this", ".", "reserved6", "=", "buffer", ".", "readUInt32BE", "(", "offset", "+", "60", ")", "this", ".", "checksum", ".", "parse", "(", "buffer", ",", "offset", "+", "64", ")", "this", ".", "blockCount", "=", "buffer", ".", "readUInt32BE", "(", "offset", "+", "200", ")", "this", ".", "blocks", "=", "[", "]", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "blockCount", ";", "i", "++", ")", "{", "this", ".", "blocks", ".", "push", "(", "BlockMap", ".", "Block", ".", "parse", "(", "buffer", ",", "offset", "+", "204", "+", "(", "i", "*", "40", ")", ")", ")", "}", "return", "this", "}" ]
Parse BlockMap data from a buffer @param {Buffer} buffer @param {Number} [offset=0] @returns {BlockMap}
[ "Parse", "BlockMap", "data", "from", "a", "buffer" ]
1f5ee84d617e8ebafc8740aec0a734602a1e8b13
https://github.com/jhermsmeier/node-udif/blob/1f5ee84d617e8ebafc8740aec0a734602a1e8b13/lib/blockmap.js#L73-L109
train
bholloway/persistent-cache-webpack-plugin
lib/encode.js
encode
function encode(object, path, exclusions) { var failed = [], result = {}; // ensure valid path and exclusions path = path || []; exclusions = exclusions || []; // enumerable properties for (var key in object) { var value = object[key]; // objects if (value && (typeof value === 'object') && (exclusions.indexOf(value) < 0)) { var className = classes.getName(value), analysis = /function ([^\(]+)\(/.exec(Function.prototype.toString.call(value.constructor)), qualifiedName = ((key.length < 60) ? key : key.slice(0, 30) + '...' + key.slice(-30)) + ':' + (className ? className.split(/[\\\/]/).pop().split('.').shift() : (analysis && analysis[1] || Object.prototype.toString.apply(value).slice(8, -1))), propPath = path.concat(qualifiedName); // add to exclusions before recursing exclusions.push(value); // depth first var recursed = encode(value, propPath, exclusions); // propagate failures but don't keep them in the tree if (recursed.$failed) { failed.push.apply(failed, recursed.$failed); delete recursed.$failed; } // exclude deleted fields if (recursed.$deleted) { failed.push(['read-only-prop ' + qualifiedName + '.' + recursed.$deleted] .concat(propPath) .concat(recursed.$deleted)); } // encode recognised class else if (className) { result[key] = { $class: className, $props: recursed }; } // include otherwise else { // unrecognised custom class if (!isPlainObject(value) && !Array.isArray(value)) { failed.push(['unknown-custom-class ' + qualifiedName].concat(propPath)); } // default to plain object result[key] = recursed; } } // include non-objects else { result[key] = value; } } // mark failures if (failed.length) { result.$failed = failed; } // complete return result; }
javascript
function encode(object, path, exclusions) { var failed = [], result = {}; // ensure valid path and exclusions path = path || []; exclusions = exclusions || []; // enumerable properties for (var key in object) { var value = object[key]; // objects if (value && (typeof value === 'object') && (exclusions.indexOf(value) < 0)) { var className = classes.getName(value), analysis = /function ([^\(]+)\(/.exec(Function.prototype.toString.call(value.constructor)), qualifiedName = ((key.length < 60) ? key : key.slice(0, 30) + '...' + key.slice(-30)) + ':' + (className ? className.split(/[\\\/]/).pop().split('.').shift() : (analysis && analysis[1] || Object.prototype.toString.apply(value).slice(8, -1))), propPath = path.concat(qualifiedName); // add to exclusions before recursing exclusions.push(value); // depth first var recursed = encode(value, propPath, exclusions); // propagate failures but don't keep them in the tree if (recursed.$failed) { failed.push.apply(failed, recursed.$failed); delete recursed.$failed; } // exclude deleted fields if (recursed.$deleted) { failed.push(['read-only-prop ' + qualifiedName + '.' + recursed.$deleted] .concat(propPath) .concat(recursed.$deleted)); } // encode recognised class else if (className) { result[key] = { $class: className, $props: recursed }; } // include otherwise else { // unrecognised custom class if (!isPlainObject(value) && !Array.isArray(value)) { failed.push(['unknown-custom-class ' + qualifiedName].concat(propPath)); } // default to plain object result[key] = recursed; } } // include non-objects else { result[key] = value; } } // mark failures if (failed.length) { result.$failed = failed; } // complete return result; }
[ "function", "encode", "(", "object", ",", "path", ",", "exclusions", ")", "{", "var", "failed", "=", "[", "]", ",", "result", "=", "{", "}", ";", "path", "=", "path", "||", "[", "]", ";", "exclusions", "=", "exclusions", "||", "[", "]", ";", "for", "(", "var", "key", "in", "object", ")", "{", "var", "value", "=", "object", "[", "key", "]", ";", "if", "(", "value", "&&", "(", "typeof", "value", "===", "'object'", ")", "&&", "(", "exclusions", ".", "indexOf", "(", "value", ")", "<", "0", ")", ")", "{", "var", "className", "=", "classes", ".", "getName", "(", "value", ")", ",", "analysis", "=", "/", "function ([^\\(]+)\\(", "/", ".", "exec", "(", "Function", ".", "prototype", ".", "toString", ".", "call", "(", "value", ".", "constructor", ")", ")", ",", "qualifiedName", "=", "(", "(", "key", ".", "length", "<", "60", ")", "?", "key", ":", "key", ".", "slice", "(", "0", ",", "30", ")", "+", "'...'", "+", "key", ".", "slice", "(", "-", "30", ")", ")", "+", "':'", "+", "(", "className", "?", "className", ".", "split", "(", "/", "[\\\\\\/]", "/", ")", ".", "pop", "(", ")", ".", "split", "(", "'.'", ")", ".", "shift", "(", ")", ":", "(", "analysis", "&&", "analysis", "[", "1", "]", "||", "Object", ".", "prototype", ".", "toString", ".", "apply", "(", "value", ")", ".", "slice", "(", "8", ",", "-", "1", ")", ")", ")", ",", "propPath", "=", "path", ".", "concat", "(", "qualifiedName", ")", ";", "exclusions", ".", "push", "(", "value", ")", ";", "var", "recursed", "=", "encode", "(", "value", ",", "propPath", ",", "exclusions", ")", ";", "if", "(", "recursed", ".", "$failed", ")", "{", "failed", ".", "push", ".", "apply", "(", "failed", ",", "recursed", ".", "$failed", ")", ";", "delete", "recursed", ".", "$failed", ";", "}", "if", "(", "recursed", ".", "$deleted", ")", "{", "failed", ".", "push", "(", "[", "'read-only-prop '", "+", "qualifiedName", "+", "'.'", "+", "recursed", ".", "$deleted", "]", ".", "concat", "(", "propPath", ")", ".", "concat", "(", "recursed", ".", "$deleted", ")", ")", ";", "}", "else", "if", "(", "className", ")", "{", "result", "[", "key", "]", "=", "{", "$class", ":", "className", ",", "$props", ":", "recursed", "}", ";", "}", "else", "{", "if", "(", "!", "isPlainObject", "(", "value", ")", "&&", "!", "Array", ".", "isArray", "(", "value", ")", ")", "{", "failed", ".", "push", "(", "[", "'unknown-custom-class '", "+", "qualifiedName", "]", ".", "concat", "(", "propPath", ")", ")", ";", "}", "result", "[", "key", "]", "=", "recursed", ";", "}", "}", "else", "{", "result", "[", "key", "]", "=", "value", ";", "}", "}", "if", "(", "failed", ".", "length", ")", "{", "result", ".", "$failed", "=", "failed", ";", "}", "return", "result", ";", "}" ]
Encode the given acyclic object with class information. @param {object} object The object to encode @param {Array.<string>} [path] Optional path information for the object where it is nested in another object @param {Array.<object>} [exclusions] Optional object list to detect circular references @returns {object} An acyclic object with additional encoded inforation
[ "Encode", "the", "given", "acyclic", "object", "with", "class", "information", "." ]
bd5aec58b1b38477218dcdc0fb144c6981604fa8
https://github.com/bholloway/persistent-cache-webpack-plugin/blob/bd5aec58b1b38477218dcdc0fb144c6981604fa8/lib/encode.js#L14-L86
train
openbiz/openbiz
lib/routers/ModelRouter.js
function(routePrefix, modelController, permission){ var routes = {}; /** if the given controller is not an instance of openbiz ModelController we will not generate it */ if(modelController instanceof openbiz.ModelController){ routes["post "+routePrefix] = [modelController.create]; routes["get "+routePrefix+"/:id"] = [modelController.exsureExists, modelController.create]; routes["put "+routePrefix+"/:id"] = [modelController.exsureExists, modelController.create]; routes["delete "+routePrefix+"/:id"] = [modelController.exsureExists, modelController.create]; /** if preset a permission , then unshift a middle-ware to all routes */ if(typeof permission != 'undefined') { var permissionMiddleware = openbiz.ensurePermission(permission); for(var route in routes) { routes[route].unshift(permissionMiddleware); } } } return routes; }
javascript
function(routePrefix, modelController, permission){ var routes = {}; /** if the given controller is not an instance of openbiz ModelController we will not generate it */ if(modelController instanceof openbiz.ModelController){ routes["post "+routePrefix] = [modelController.create]; routes["get "+routePrefix+"/:id"] = [modelController.exsureExists, modelController.create]; routes["put "+routePrefix+"/:id"] = [modelController.exsureExists, modelController.create]; routes["delete "+routePrefix+"/:id"] = [modelController.exsureExists, modelController.create]; /** if preset a permission , then unshift a middle-ware to all routes */ if(typeof permission != 'undefined') { var permissionMiddleware = openbiz.ensurePermission(permission); for(var route in routes) { routes[route].unshift(permissionMiddleware); } } } return routes; }
[ "function", "(", "routePrefix", ",", "modelController", ",", "permission", ")", "{", "var", "routes", "=", "{", "}", ";", "if", "(", "modelController", "instanceof", "openbiz", ".", "ModelController", ")", "{", "routes", "[", "\"post \"", "+", "routePrefix", "]", "=", "[", "modelController", ".", "create", "]", ";", "routes", "[", "\"get \"", "+", "routePrefix", "+", "\"/:id\"", "]", "=", "[", "modelController", ".", "exsureExists", ",", "modelController", ".", "create", "]", ";", "routes", "[", "\"put \"", "+", "routePrefix", "+", "\"/:id\"", "]", "=", "[", "modelController", ".", "exsureExists", ",", "modelController", ".", "create", "]", ";", "routes", "[", "\"delete \"", "+", "routePrefix", "+", "\"/:id\"", "]", "=", "[", "modelController", ".", "exsureExists", ",", "modelController", ".", "create", "]", ";", "if", "(", "typeof", "permission", "!=", "'undefined'", ")", "{", "var", "permissionMiddleware", "=", "openbiz", ".", "ensurePermission", "(", "permission", ")", ";", "for", "(", "var", "route", "in", "routes", ")", "{", "routes", "[", "route", "]", ".", "unshift", "(", "permissionMiddleware", ")", ";", "}", "}", "}", "return", "routes", ";", "}" ]
Generate default routes for standard data modal @static @memberof openbiz.routers.ModelRouter @param {string} routePrefix - the route name of this resource @param {openbiz.controllers.ModelController} modelController - the controller which map this route to @param {string} [permission] - the permission which default to protect this resource @return {object} Route rules object @example //inside a module router e.g. /cubi/routes/account.js var routes = openbiz.ModelRouter.getDefaultRoutes('/accounts', openbiz.getController(cubi.account.AccountCountroller), 'cubi-account-manage'); module.exports = routes; // routes entity will looks like below: // { // "post /accounts" : [ openbiz.ensurePermission("cubi-account-manage"), // openbiz.getController("cubi.account.AccountController").create], // // "get /accounts/:id" : [ openbiz.ensurePermission("cubi-account-manage"), // openbiz.getController("cubi.account.AccountController").ensureExists, // openbiz.getController("cubi.account.AccountController").findById], // // "put /accounts/:id" : [ openbiz.ensurePermission("cubi-account-manage"), // openbiz.getController("cubi.account.AccountController").ensureExists, // openbiz.getController("cubi.account.AccountController").update], // // "delete /accounts/:id" : [ openbiz.ensurePermission("cubi-account-manage"), // openbiz.getController("cubi.account.AccountController").ensureExists, // openbiz.getController("cubi.account.AccountController").delete], // }
[ "Generate", "default", "routes", "for", "standard", "data", "modal" ]
997f1398396683d7ad667b1b360ce74c7c7fcf6f
https://github.com/openbiz/openbiz/blob/997f1398396683d7ad667b1b360ce74c7c7fcf6f/lib/routers/ModelRouter.js#L42-L62
train
harvest-platform/harvest-api-client
src/client.js
parseLinks
function parseLinks(target, resp) { target._links = parseLinkHeader(resp.headers.get('link')); target._linkTemplates = parseLinkHeader(resp.headers.get('link-template')); return resp }
javascript
function parseLinks(target, resp) { target._links = parseLinkHeader(resp.headers.get('link')); target._linkTemplates = parseLinkHeader(resp.headers.get('link-template')); return resp }
[ "function", "parseLinks", "(", "target", ",", "resp", ")", "{", "target", ".", "_links", "=", "parseLinkHeader", "(", "resp", ".", "headers", ".", "get", "(", "'link'", ")", ")", ";", "target", ".", "_linkTemplates", "=", "parseLinkHeader", "(", "resp", ".", "headers", ".", "get", "(", "'link-template'", ")", ")", ";", "return", "resp", "}" ]
Parse Link and Link-Template headers and set them on the target.
[ "Parse", "Link", "and", "Link", "-", "Template", "headers", "and", "set", "them", "on", "the", "target", "." ]
ff5af21f446cd68c69e005c9a5911faad353fb63
https://github.com/harvest-platform/harvest-api-client/blob/ff5af21f446cd68c69e005c9a5911faad353fb63/src/client.js#L13-L17
train
harvest-platform/harvest-api-client
src/client.js
throwStatusError
function throwStatusError(resp) { let err = new Error(resp.statusText || 'http error: ' + resp.status); err.type = resp.status; err.response = resp; err.url = resp.url; throw err; }
javascript
function throwStatusError(resp) { let err = new Error(resp.statusText || 'http error: ' + resp.status); err.type = resp.status; err.response = resp; err.url = resp.url; throw err; }
[ "function", "throwStatusError", "(", "resp", ")", "{", "let", "err", "=", "new", "Error", "(", "resp", ".", "statusText", "||", "'http error: '", "+", "resp", ".", "status", ")", ";", "err", ".", "type", "=", "resp", ".", "status", ";", "err", ".", "response", "=", "resp", ";", "err", ".", "url", "=", "resp", ".", "url", ";", "throw", "err", ";", "}" ]
Constructs and throws a response status error.
[ "Constructs", "and", "throws", "a", "response", "status", "error", "." ]
ff5af21f446cd68c69e005c9a5911faad353fb63
https://github.com/harvest-platform/harvest-api-client/blob/ff5af21f446cd68c69e005c9a5911faad353fb63/src/client.js#L24-L30
train
harvest-platform/harvest-api-client
src/client.js
throwTimeoutError
function throwTimeoutError(resp) { let err = new Error('timeout'); err.type = 'timeout'; err.response = resp; err.url = resp.url; throw err; }
javascript
function throwTimeoutError(resp) { let err = new Error('timeout'); err.type = 'timeout'; err.response = resp; err.url = resp.url; throw err; }
[ "function", "throwTimeoutError", "(", "resp", ")", "{", "let", "err", "=", "new", "Error", "(", "'timeout'", ")", ";", "err", ".", "type", "=", "'timeout'", ";", "err", ".", "response", "=", "resp", ";", "err", ".", "url", "=", "resp", ".", "url", ";", "throw", "err", ";", "}" ]
Constructs and throws a timeout-based error.
[ "Constructs", "and", "throws", "a", "timeout", "-", "based", "error", "." ]
ff5af21f446cd68c69e005c9a5911faad353fb63
https://github.com/harvest-platform/harvest-api-client/blob/ff5af21f446cd68c69e005c9a5911faad353fb63/src/client.js#L33-L39
train
LaunchPadLab/lp-redux-api
src/handlers/set-on-response.js
setOnResponse
function setOnResponse ( successPath, failurePath, transformSuccess=getDataFromAction, transformFailure=getDataFromAction, ) { return handleResponse( (state, action) => set(successPath, transformSuccess(action, state), state), (state, action) => set(failurePath, transformFailure(action, state), state), ) }
javascript
function setOnResponse ( successPath, failurePath, transformSuccess=getDataFromAction, transformFailure=getDataFromAction, ) { return handleResponse( (state, action) => set(successPath, transformSuccess(action, state), state), (state, action) => set(failurePath, transformFailure(action, state), state), ) }
[ "function", "setOnResponse", "(", "successPath", ",", "failurePath", ",", "transformSuccess", "=", "getDataFromAction", ",", "transformFailure", "=", "getDataFromAction", ",", ")", "{", "return", "handleResponse", "(", "(", "state", ",", "action", ")", "=>", "set", "(", "successPath", ",", "transformSuccess", "(", "action", ",", "state", ")", ",", "state", ")", ",", "(", "state", ",", "action", ")", "=>", "set", "(", "failurePath", ",", "transformFailure", "(", "action", ",", "state", ")", ",", "state", ")", ",", ")", "}" ]
A function that creates an API action handler that sets one of two given paths in the state with the returned data depending on whether a request succeeds or fails. @name setOnResponse @param {String} path - The path in the state to set with the returned data on success @param {String} path - The path in the state to set with the returned error on failure @param {Function} [transform] - A function that determines the success data that is set in the state. Passed `action` and `state` params. @param {Function} [transform] - A function that determines the error data that is set in the state. Passed `action` and `state` params. @returns {Function} An action handler @example handleActions({ // This will do the same thing as the example for handleResponse [apiActions.fetchUser]: setOnResponse('currentUser', 'userFetchError') })
[ "A", "function", "that", "creates", "an", "API", "action", "handler", "that", "sets", "one", "of", "two", "given", "paths", "in", "the", "state", "with", "the", "returned", "data", "depending", "on", "whether", "a", "request", "succeeds", "or", "fails", "." ]
73eee231067365326780ddc1dbbfa50d3e65defc
https://github.com/LaunchPadLab/lp-redux-api/blob/73eee231067365326780ddc1dbbfa50d3e65defc/src/handlers/set-on-response.js#L23-L33
train
junghans-schneider/extjs-dependencies
lib/resolver.js
function(rootPath, filePath, encoding) { return fs.readFileSync(path.resolve(rootPath, filePath), encoding || 'utf8'); }
javascript
function(rootPath, filePath, encoding) { return fs.readFileSync(path.resolve(rootPath, filePath), encoding || 'utf8'); }
[ "function", "(", "rootPath", ",", "filePath", ",", "encoding", ")", "{", "return", "fs", ".", "readFileSync", "(", "path", ".", "resolve", "(", "rootPath", ",", "filePath", ")", ",", "encoding", "||", "'utf8'", ")", ";", "}" ]
Returns an object representing the content of a file. @param rootPath {string} the root path of the project @param filePath {string} the path of the file (relative to rootPath) @param encoding {string?} the encoding to use (is null if a default should be used) @return {object} an object representing the content.
[ "Returns", "an", "object", "representing", "the", "content", "of", "a", "file", "." ]
be36e87339b0973883c490fe2535414e74b1413b
https://github.com/junghans-schneider/extjs-dependencies/blob/be36e87339b0973883c490fe2535414e74b1413b/lib/resolver.js#L25-L27
train
junghans-schneider/extjs-dependencies
lib/resolver.js
resolve
function resolve(options) { options = extend({ root: '.', fileProvider: defaultFileProvider }, options); var context = { options: options, parser: new Parser({ excludeClasses: options.excludeClasses, skipParse: options.skipParse, extraDependencies: options.extraDependencies, parserOptions: options.parserOptions }), classNameByAlias: {}, // maps alias className (String) to its real className (String) providedFileInfoByClassName: {}, // maps className (String) to fileInfo (ExtClass) for provided files fileInfoByPath: {}, // maps filePath (String) to fileInfo (ExtClass) for files to include fileInfoByClassName: {}, // maps className (String) to fileInfo (ExtClass) for files to include fileInfos: [] }; var providedOption = options.provided; if (providedOption) { toArray(providedOption).forEach(function(path) { markProvided(path, context) }); } toArray(options.entry).forEach(function(path) { collectDependencies(path, context) }); return orderFileInfo(context); }
javascript
function resolve(options) { options = extend({ root: '.', fileProvider: defaultFileProvider }, options); var context = { options: options, parser: new Parser({ excludeClasses: options.excludeClasses, skipParse: options.skipParse, extraDependencies: options.extraDependencies, parserOptions: options.parserOptions }), classNameByAlias: {}, // maps alias className (String) to its real className (String) providedFileInfoByClassName: {}, // maps className (String) to fileInfo (ExtClass) for provided files fileInfoByPath: {}, // maps filePath (String) to fileInfo (ExtClass) for files to include fileInfoByClassName: {}, // maps className (String) to fileInfo (ExtClass) for files to include fileInfos: [] }; var providedOption = options.provided; if (providedOption) { toArray(providedOption).forEach(function(path) { markProvided(path, context) }); } toArray(options.entry).forEach(function(path) { collectDependencies(path, context) }); return orderFileInfo(context); }
[ "function", "resolve", "(", "options", ")", "{", "options", "=", "extend", "(", "{", "root", ":", "'.'", ",", "fileProvider", ":", "defaultFileProvider", "}", ",", "options", ")", ";", "var", "context", "=", "{", "options", ":", "options", ",", "parser", ":", "new", "Parser", "(", "{", "excludeClasses", ":", "options", ".", "excludeClasses", ",", "skipParse", ":", "options", ".", "skipParse", ",", "extraDependencies", ":", "options", ".", "extraDependencies", ",", "parserOptions", ":", "options", ".", "parserOptions", "}", ")", ",", "classNameByAlias", ":", "{", "}", ",", "providedFileInfoByClassName", ":", "{", "}", ",", "fileInfoByPath", ":", "{", "}", ",", "fileInfoByClassName", ":", "{", "}", ",", "fileInfos", ":", "[", "]", "}", ";", "var", "providedOption", "=", "options", ".", "provided", ";", "if", "(", "providedOption", ")", "{", "toArray", "(", "providedOption", ")", ".", "forEach", "(", "function", "(", "path", ")", "{", "markProvided", "(", "path", ",", "context", ")", "}", ")", ";", "}", "toArray", "(", "options", ".", "entry", ")", ".", "forEach", "(", "function", "(", "path", ")", "{", "collectDependencies", "(", "path", ",", "context", ")", "}", ")", ";", "return", "orderFileInfo", "(", "context", ")", ";", "}" ]
Resolves and sorts all dependencies of an Ext JS project. @param options Example: { // Log verbose? Optional, default is false. verbose: false, // Source file encoding. Default: 'utf8' encoding: 'utf8', // The root of your project. All paths are relative to this. Default: '.' root: 'path/to/project', // Add Ext JS scripts you load independently in your html file. provided: [ 'extjs/ext-dev.js' ], // Add all entry points to include with dependencies entry: [ 'app.js' ], resolve: { // The source folders for each class name prefix. Optional. path: { 'Ext': 'ext/src', 'myapp': 'app' }, // Alternative class names. Optional. alias: { 'Ext.Layer': 'Ext.dom.Layer' } }, // Optimize source? (removes some statements like `require`) Optional. Default is false. optimizeSource: false, // Extra dependencies. Optional. extraDependencies: { requires: { 'MyClass': 'MyDependency' }, uses: { 'MyClass': 'MyDependency' } } // Classes to exclude. Optional. excludeClasses: ['Ext.*', 'MyApp.some.Class'], // Files to exclude (excludes also dependencies). Optional. skipParse: ['app/ux/SkipMe.js'], // The file provider to use. Optional. fileProvider: { // Returns an object representing the content of a file. createFileContent: function(rootPath, filePath, encoding) { ... }, // Returns the content of a file as string. getContentAsString: function(content) { ... } } } @return The dependencies as array of ExtClass in correct loading order
[ "Resolves", "and", "sorts", "all", "dependencies", "of", "an", "Ext", "JS", "project", "." ]
be36e87339b0973883c490fe2535414e74b1413b
https://github.com/junghans-schneider/extjs-dependencies/blob/be36e87339b0973883c490fe2535414e74b1413b/lib/resolver.js#L105-L138
train
axke/rs-api
lib/apis/clan.js
Clan
function Clan(config) { //Read the clans data from a csv to an array object var readClan = function(data) { var members = [], space = new RegExp(String.fromCharCode(65533), 'g'); for (var i = 1; i < data.length; i++) { var member = data[i]; members.push({ player: member[0].replace(space, ' '), rank: member[1], exp: Number(member[2]), kills: Number(member[3]) }); } return members; }; /** * Get a clans member list with exp gained and total kills (available for `rs`) * @param name The clans name * @returns {Object} Member list * @example * api.rs.hiscores.clan('Efficiency Experts').then(function(clan) { * console.log(clan); * }).catch(console.error); */ this.members = function(name) { return new Promise(function(resolve, reject) { if (typeof config.urls.members === 'undefined') { reject(new Error('Oldschool RuneScape does not have clans.')); return; } request.csv(config.urls.members + encodeURIComponent(name)).then(function(data) { resolve(readClan(data)); }).catch(reject); }); }; }
javascript
function Clan(config) { //Read the clans data from a csv to an array object var readClan = function(data) { var members = [], space = new RegExp(String.fromCharCode(65533), 'g'); for (var i = 1; i < data.length; i++) { var member = data[i]; members.push({ player: member[0].replace(space, ' '), rank: member[1], exp: Number(member[2]), kills: Number(member[3]) }); } return members; }; /** * Get a clans member list with exp gained and total kills (available for `rs`) * @param name The clans name * @returns {Object} Member list * @example * api.rs.hiscores.clan('Efficiency Experts').then(function(clan) { * console.log(clan); * }).catch(console.error); */ this.members = function(name) { return new Promise(function(resolve, reject) { if (typeof config.urls.members === 'undefined') { reject(new Error('Oldschool RuneScape does not have clans.')); return; } request.csv(config.urls.members + encodeURIComponent(name)).then(function(data) { resolve(readClan(data)); }).catch(reject); }); }; }
[ "function", "Clan", "(", "config", ")", "{", "var", "readClan", "=", "function", "(", "data", ")", "{", "var", "members", "=", "[", "]", ",", "space", "=", "new", "RegExp", "(", "String", ".", "fromCharCode", "(", "65533", ")", ",", "'g'", ")", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<", "data", ".", "length", ";", "i", "++", ")", "{", "var", "member", "=", "data", "[", "i", "]", ";", "members", ".", "push", "(", "{", "player", ":", "member", "[", "0", "]", ".", "replace", "(", "space", ",", "' '", ")", ",", "rank", ":", "member", "[", "1", "]", ",", "exp", ":", "Number", "(", "member", "[", "2", "]", ")", ",", "kills", ":", "Number", "(", "member", "[", "3", "]", ")", "}", ")", ";", "}", "return", "members", ";", "}", ";", "this", ".", "members", "=", "function", "(", "name", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "if", "(", "typeof", "config", ".", "urls", ".", "members", "===", "'undefined'", ")", "{", "reject", "(", "new", "Error", "(", "'Oldschool RuneScape does not have clans.'", ")", ")", ";", "return", ";", "}", "request", ".", "csv", "(", "config", ".", "urls", ".", "members", "+", "encodeURIComponent", "(", "name", ")", ")", ".", "then", "(", "function", "(", "data", ")", "{", "resolve", "(", "readClan", "(", "data", ")", ")", ";", "}", ")", ".", "catch", "(", "reject", ")", ";", "}", ")", ";", "}", ";", "}" ]
Module containing Clan functions @module Clan
[ "Module", "containing", "Clan", "functions" ]
71af4973e1d079f09b7d888b6d24735784185942
https://github.com/axke/rs-api/blob/71af4973e1d079f09b7d888b6d24735784185942/lib/apis/clan.js#L10-L51
train
axke/rs-api
lib/apis/clan.js
function(data) { var members = [], space = new RegExp(String.fromCharCode(65533), 'g'); for (var i = 1; i < data.length; i++) { var member = data[i]; members.push({ player: member[0].replace(space, ' '), rank: member[1], exp: Number(member[2]), kills: Number(member[3]) }); } return members; }
javascript
function(data) { var members = [], space = new RegExp(String.fromCharCode(65533), 'g'); for (var i = 1; i < data.length; i++) { var member = data[i]; members.push({ player: member[0].replace(space, ' '), rank: member[1], exp: Number(member[2]), kills: Number(member[3]) }); } return members; }
[ "function", "(", "data", ")", "{", "var", "members", "=", "[", "]", ",", "space", "=", "new", "RegExp", "(", "String", ".", "fromCharCode", "(", "65533", ")", ",", "'g'", ")", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<", "data", ".", "length", ";", "i", "++", ")", "{", "var", "member", "=", "data", "[", "i", "]", ";", "members", ".", "push", "(", "{", "player", ":", "member", "[", "0", "]", ".", "replace", "(", "space", ",", "' '", ")", ",", "rank", ":", "member", "[", "1", "]", ",", "exp", ":", "Number", "(", "member", "[", "2", "]", ")", ",", "kills", ":", "Number", "(", "member", "[", "3", "]", ")", "}", ")", ";", "}", "return", "members", ";", "}" ]
Read the clans data from a csv to an array object
[ "Read", "the", "clans", "data", "from", "a", "csv", "to", "an", "array", "object" ]
71af4973e1d079f09b7d888b6d24735784185942
https://github.com/axke/rs-api/blob/71af4973e1d079f09b7d888b6d24735784185942/lib/apis/clan.js#L13-L28
train
klaygomes/karma-typescript-preprocessor2
index.js
_serveFile
function _serveFile(requestedFile, done) { let compiled , temp = [] , wasCompiled; log.debug(`Fetching ${transformPath(requestedFile.path)} from buffer`); if (requestedFile.sha) { delete requestedFile.sha; //simple hack i used to prevent infinite loop _feedBuffer(requestedFile, done); compile(); return; } while (compiled = _compiledBuffer.shift()) { if (_normalize(compiled.path) === _normalize(requestedFile.path)) { wasCompiled = true; done(null, compiled.contents.toString()); } else { temp.unshift(compiled); } } //refeed buffer _compiledBuffer = temp; //if file was not found in the stream //maybe it is not compiled or it is a definition file, so we don't need to worry about if (!wasCompiled) { log.debug(`${requestedFile.originalPath} was not found. Maybe it was not compiled or it is a definition file.`); done(null, dummyFile("This file was not compiled")); } }
javascript
function _serveFile(requestedFile, done) { let compiled , temp = [] , wasCompiled; log.debug(`Fetching ${transformPath(requestedFile.path)} from buffer`); if (requestedFile.sha) { delete requestedFile.sha; //simple hack i used to prevent infinite loop _feedBuffer(requestedFile, done); compile(); return; } while (compiled = _compiledBuffer.shift()) { if (_normalize(compiled.path) === _normalize(requestedFile.path)) { wasCompiled = true; done(null, compiled.contents.toString()); } else { temp.unshift(compiled); } } //refeed buffer _compiledBuffer = temp; //if file was not found in the stream //maybe it is not compiled or it is a definition file, so we don't need to worry about if (!wasCompiled) { log.debug(`${requestedFile.originalPath} was not found. Maybe it was not compiled or it is a definition file.`); done(null, dummyFile("This file was not compiled")); } }
[ "function", "_serveFile", "(", "requestedFile", ",", "done", ")", "{", "let", "compiled", ",", "temp", "=", "[", "]", ",", "wasCompiled", ";", "log", ".", "debug", "(", "`", "${", "transformPath", "(", "requestedFile", ".", "path", ")", "}", "`", ")", ";", "if", "(", "requestedFile", ".", "sha", ")", "{", "delete", "requestedFile", ".", "sha", ";", "_feedBuffer", "(", "requestedFile", ",", "done", ")", ";", "compile", "(", ")", ";", "return", ";", "}", "while", "(", "compiled", "=", "_compiledBuffer", ".", "shift", "(", ")", ")", "{", "if", "(", "_normalize", "(", "compiled", ".", "path", ")", "===", "_normalize", "(", "requestedFile", ".", "path", ")", ")", "{", "wasCompiled", "=", "true", ";", "done", "(", "null", ",", "compiled", ".", "contents", ".", "toString", "(", ")", ")", ";", "}", "else", "{", "temp", ".", "unshift", "(", "compiled", ")", ";", "}", "}", "_compiledBuffer", "=", "temp", ";", "if", "(", "!", "wasCompiled", ")", "{", "log", ".", "debug", "(", "`", "${", "requestedFile", ".", "originalPath", "}", "`", ")", ";", "done", "(", "null", ",", "dummyFile", "(", "\"This file was not compiled\"", ")", ")", ";", "}", "}" ]
Used to fetch files from buffer if requested file contains a sha defined, it means this file was changed by karma
[ "Used", "to", "fetch", "files", "from", "buffer", "if", "requested", "file", "contains", "a", "sha", "defined", "it", "means", "this", "file", "was", "changed", "by", "karma" ]
4a0f23efc6c309aa54d6975e6e688d0a2b165e4a
https://github.com/klaygomes/karma-typescript-preprocessor2/blob/4a0f23efc6c309aa54d6975e6e688d0a2b165e4a/index.js#L100-L133
train
Raynos/continuable
examples/docs.js
function (source, destination) { return cont.mapAsync(readFileAsJSON(source), function (json, cb) { json.copied = Date.now() fs.writeFile(destination, JSON.stringify(json), cb) }) }
javascript
function (source, destination) { return cont.mapAsync(readFileAsJSON(source), function (json, cb) { json.copied = Date.now() fs.writeFile(destination, JSON.stringify(json), cb) }) }
[ "function", "(", "source", ",", "destination", ")", "{", "return", "cont", ".", "mapAsync", "(", "readFileAsJSON", "(", "source", ")", ",", "function", "(", "json", ",", "cb", ")", "{", "json", ".", "copied", "=", "Date", ".", "now", "(", ")", "fs", ".", "writeFile", "(", "destination", ",", "JSON", ".", "stringify", "(", "json", ")", ",", "cb", ")", "}", ")", "}" ]
mapAsync takes an asynchronous transformation function and a source continuable. The new continuable is the value of the first continuable passed through the async transformation.
[ "mapAsync", "takes", "an", "asynchronous", "transformation", "function", "and", "a", "source", "continuable", ".", "The", "new", "continuable", "is", "the", "value", "of", "the", "first", "continuable", "passed", "through", "the", "async", "transformation", "." ]
f2e2ce2e2ce596a945f784f8942db35a9fbe1e60
https://github.com/Raynos/continuable/blob/f2e2ce2e2ce596a945f784f8942db35a9fbe1e60/examples/docs.js#L105-L110
train
sballesteros/dcat
index.js
_getStatsAndParts
function _getStatsAndParts (tp, cb){ fs.stat(tp.absPath, function(err, stats){ if (err) return cb(err); if (stats.isDirectory) { glob(path.join(tp.absPath, '**/*'), function(err, dirAbsPaths){ if (err) return cb(err); async.map(dirAbsPaths, fs.stat, function(err, dirAbsPathStats){ if (err) return cb(err); var parts = dirAbsPathStats .map(function(x, i){ return {stats: x, absPath: dirAbsPaths[i]}; }) .filter(function(x){ return x.stats.isFile(); }); cb(null, stats, parts); }); }); } else { return cb(null, stats); } }); }
javascript
function _getStatsAndParts (tp, cb){ fs.stat(tp.absPath, function(err, stats){ if (err) return cb(err); if (stats.isDirectory) { glob(path.join(tp.absPath, '**/*'), function(err, dirAbsPaths){ if (err) return cb(err); async.map(dirAbsPaths, fs.stat, function(err, dirAbsPathStats){ if (err) return cb(err); var parts = dirAbsPathStats .map(function(x, i){ return {stats: x, absPath: dirAbsPaths[i]}; }) .filter(function(x){ return x.stats.isFile(); }); cb(null, stats, parts); }); }); } else { return cb(null, stats); } }); }
[ "function", "_getStatsAndParts", "(", "tp", ",", "cb", ")", "{", "fs", ".", "stat", "(", "tp", ".", "absPath", ",", "function", "(", "err", ",", "stats", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "if", "(", "stats", ".", "isDirectory", ")", "{", "glob", "(", "path", ".", "join", "(", "tp", ".", "absPath", ",", "'**/*'", ")", ",", "function", "(", "err", ",", "dirAbsPaths", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "async", ".", "map", "(", "dirAbsPaths", ",", "fs", ".", "stat", ",", "function", "(", "err", ",", "dirAbsPathStats", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "var", "parts", "=", "dirAbsPathStats", ".", "map", "(", "function", "(", "x", ",", "i", ")", "{", "return", "{", "stats", ":", "x", ",", "absPath", ":", "dirAbsPaths", "[", "i", "]", "}", ";", "}", ")", ".", "filter", "(", "function", "(", "x", ")", "{", "return", "x", ".", "stats", ".", "isFile", "(", ")", ";", "}", ")", ";", "cb", "(", "null", ",", "stats", ",", "parts", ")", ";", "}", ")", ";", "}", ")", ";", "}", "else", "{", "return", "cb", "(", "null", ",", "stats", ")", ";", "}", "}", ")", ";", "}" ]
transform abs paths to resources and make source each resource has a unique @id
[ "transform", "abs", "paths", "to", "resources", "and", "make", "source", "each", "resource", "has", "a", "unique" ]
21a2b99c03e55f192aa390b915e340e021eb19c6
https://github.com/sballesteros/dcat/blob/21a2b99c03e55f192aa390b915e340e021eb19c6/index.js#L277-L295
train
sballesteros/dcat
index.js
_check
function _check(mnode, cb){ if (mnode.node.filePath) { fs.stat(path.resolve(root, mnode.node.filePath), function(err, stats){ if (err) return cb(err); mnode.node.dateModified = stats.mtime.toISOString(); if (psize) { mnode.node[psize] = stats.size; } cb(null); }); } else if (mnode.node.hasPart) { var hasPart = (Array.isArray(mnode.node.hasPart)) ? mnode.node.hasPart : [mnode.node.hasPart]; async.each(hasPart, function(part, cb2){ if (part.filePath) { fs.stat(path.resolve(root, part.filePath), function(err, stats){ if (err) return cb2(err); part.dateModified = stats.mtime.toISOString(); var type = packager.getType(part, packager.getRanges('hasPart')); var isSoftwareApplication = type && packager.isClassOrSubClassOf(type, 'SoftwareApplication'); var isMediaObject = type && packager.isClassOrSubClassOf(type, 'MediaObject'); if (isSoftwareApplication) { part.fileSize = stats.size; } else if (isMediaObject) { part.contentSize = stats.size; } cb2(null); }); } else { cb2(null); } }, cb); } else { cb(null); } }
javascript
function _check(mnode, cb){ if (mnode.node.filePath) { fs.stat(path.resolve(root, mnode.node.filePath), function(err, stats){ if (err) return cb(err); mnode.node.dateModified = stats.mtime.toISOString(); if (psize) { mnode.node[psize] = stats.size; } cb(null); }); } else if (mnode.node.hasPart) { var hasPart = (Array.isArray(mnode.node.hasPart)) ? mnode.node.hasPart : [mnode.node.hasPart]; async.each(hasPart, function(part, cb2){ if (part.filePath) { fs.stat(path.resolve(root, part.filePath), function(err, stats){ if (err) return cb2(err); part.dateModified = stats.mtime.toISOString(); var type = packager.getType(part, packager.getRanges('hasPart')); var isSoftwareApplication = type && packager.isClassOrSubClassOf(type, 'SoftwareApplication'); var isMediaObject = type && packager.isClassOrSubClassOf(type, 'MediaObject'); if (isSoftwareApplication) { part.fileSize = stats.size; } else if (isMediaObject) { part.contentSize = stats.size; } cb2(null); }); } else { cb2(null); } }, cb); } else { cb(null); } }
[ "function", "_check", "(", "mnode", ",", "cb", ")", "{", "if", "(", "mnode", ".", "node", ".", "filePath", ")", "{", "fs", ".", "stat", "(", "path", ".", "resolve", "(", "root", ",", "mnode", ".", "node", ".", "filePath", ")", ",", "function", "(", "err", ",", "stats", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "mnode", ".", "node", ".", "dateModified", "=", "stats", ".", "mtime", ".", "toISOString", "(", ")", ";", "if", "(", "psize", ")", "{", "mnode", ".", "node", "[", "psize", "]", "=", "stats", ".", "size", ";", "}", "cb", "(", "null", ")", ";", "}", ")", ";", "}", "else", "if", "(", "mnode", ".", "node", ".", "hasPart", ")", "{", "var", "hasPart", "=", "(", "Array", ".", "isArray", "(", "mnode", ".", "node", ".", "hasPart", ")", ")", "?", "mnode", ".", "node", ".", "hasPart", ":", "[", "mnode", ".", "node", ".", "hasPart", "]", ";", "async", ".", "each", "(", "hasPart", ",", "function", "(", "part", ",", "cb2", ")", "{", "if", "(", "part", ".", "filePath", ")", "{", "fs", ".", "stat", "(", "path", ".", "resolve", "(", "root", ",", "part", ".", "filePath", ")", ",", "function", "(", "err", ",", "stats", ")", "{", "if", "(", "err", ")", "return", "cb2", "(", "err", ")", ";", "part", ".", "dateModified", "=", "stats", ".", "mtime", ".", "toISOString", "(", ")", ";", "var", "type", "=", "packager", ".", "getType", "(", "part", ",", "packager", ".", "getRanges", "(", "'hasPart'", ")", ")", ";", "var", "isSoftwareApplication", "=", "type", "&&", "packager", ".", "isClassOrSubClassOf", "(", "type", ",", "'SoftwareApplication'", ")", ";", "var", "isMediaObject", "=", "type", "&&", "packager", ".", "isClassOrSubClassOf", "(", "type", ",", "'MediaObject'", ")", ";", "if", "(", "isSoftwareApplication", ")", "{", "part", ".", "fileSize", "=", "stats", ".", "size", ";", "}", "else", "if", "(", "isMediaObject", ")", "{", "part", ".", "contentSize", "=", "stats", ".", "size", ";", "}", "cb2", "(", "null", ")", ";", "}", ")", ";", "}", "else", "{", "cb2", "(", "null", ")", ";", "}", "}", ",", "cb", ")", ";", "}", "else", "{", "cb", "(", "null", ")", ";", "}", "}" ]
check that all the files are here and update dateModified and contentSize
[ "check", "that", "all", "the", "files", "are", "here", "and", "update", "dateModified", "and", "contentSize" ]
21a2b99c03e55f192aa390b915e340e021eb19c6
https://github.com/sballesteros/dcat/blob/21a2b99c03e55f192aa390b915e340e021eb19c6/index.js#L771-L806
train
oskargustafsson/BFF
src/event-emitter.js
function (eventName) { if (RUNTIME_CHECKS && typeof eventName !== 'string') { throw '"eventName" argument must be a string'; } if (!this.__private || !this.__private.listeners) { return; } var listenersForEvent = this.__private.listeners[eventName]; if (!listenersForEvent) { return; } for (var i = 0, n = listenersForEvent.length; i < n; ++i) { var listener = listenersForEvent[i]; // Call the listener without the first item in the "arguments" array listener.call.apply(listener, arguments); } }
javascript
function (eventName) { if (RUNTIME_CHECKS && typeof eventName !== 'string') { throw '"eventName" argument must be a string'; } if (!this.__private || !this.__private.listeners) { return; } var listenersForEvent = this.__private.listeners[eventName]; if (!listenersForEvent) { return; } for (var i = 0, n = listenersForEvent.length; i < n; ++i) { var listener = listenersForEvent[i]; // Call the listener without the first item in the "arguments" array listener.call.apply(listener, arguments); } }
[ "function", "(", "eventName", ")", "{", "if", "(", "RUNTIME_CHECKS", "&&", "typeof", "eventName", "!==", "'string'", ")", "{", "throw", "'\"eventName\" argument must be a string'", ";", "}", "if", "(", "!", "this", ".", "__private", "||", "!", "this", ".", "__private", ".", "listeners", ")", "{", "return", ";", "}", "var", "listenersForEvent", "=", "this", ".", "__private", ".", "listeners", "[", "eventName", "]", ";", "if", "(", "!", "listenersForEvent", ")", "{", "return", ";", "}", "for", "(", "var", "i", "=", "0", ",", "n", "=", "listenersForEvent", ".", "length", ";", "i", "<", "n", ";", "++", "i", ")", "{", "var", "listener", "=", "listenersForEvent", "[", "i", "]", ";", "listener", ".", "call", ".", "apply", "(", "listener", ",", "arguments", ")", ";", "}", "}" ]
Emit an event. Callbacks will be called with the same arguments as this function was called with, except for the event name argument. @instance @arg {string} eventName - Identifier string for the event. @arg {...any} [eventArguments] - Zero or more arguments that event listeners will be called with.
[ "Emit", "an", "event", ".", "Callbacks", "will", "be", "called", "with", "the", "same", "arguments", "as", "this", "function", "was", "called", "with", "except", "for", "the", "event", "name", "argument", "." ]
38ebebf3b69f758da78ffb50a97742d33d6d5931
https://github.com/oskargustafsson/BFF/blob/38ebebf3b69f758da78ffb50a97742d33d6d5931/src/event-emitter.js#L19-L34
train