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
acos-server/acos-kelmu
static/kelmu.js
function() { var events; var button; if (window.kelmu.data[id].settings.step && !stepButtonInitialized) { button = element.find(window.kelmu.data[id].settings.step); if (button.length > 0) { events = $._data(button[0], 'events'); stepButtonInitialized = true; if (events && events.click && events.click.length > 0) { originalStep = events.click[0].handler; events.click[0].handler = forwardAndSkip; } else { button.click(forwardAndSkip); } } } if (window.kelmu.data[id].settings.redo && !redoButtonInitialized) { button = element.find(window.kelmu.data[id].settings.redo); if (button.length > 0) { events = $._data(button[0], 'events'); redoButtonInitialized = true; if (events && events.click && events.click.length > 0) { originalRedo = events.click[0].handler; events.click[0].handler = redo; } else { button.click(redo); } } } if (window.kelmu.data[id].settings.undo && !undoButtonInitialized) { button = element.find(window.kelmu.data[id].settings.undo); if (button.length > 0) { events = $._data(button[0], 'events'); undoButtonInitialized = true; if (events && events.click && events.click.length > 0) { originalUndo = events.click[0].handler; events.click[0].handler = undo; } else { button.click(undo); } } } if (window.kelmu.data[id].settings.begin && !beginButtonInitialized) { button = element.find(window.kelmu.data[id].settings.begin); if (button.length > 0) { events = $._data(button[0], 'events'); beginButtonInitialized = true; if (events && events.click && events.click.length > 0) { originalBegin = events.click[0].handler; events.click[0].handler = begin; } else { button.click(begin); } } } }
javascript
function() { var events; var button; if (window.kelmu.data[id].settings.step && !stepButtonInitialized) { button = element.find(window.kelmu.data[id].settings.step); if (button.length > 0) { events = $._data(button[0], 'events'); stepButtonInitialized = true; if (events && events.click && events.click.length > 0) { originalStep = events.click[0].handler; events.click[0].handler = forwardAndSkip; } else { button.click(forwardAndSkip); } } } if (window.kelmu.data[id].settings.redo && !redoButtonInitialized) { button = element.find(window.kelmu.data[id].settings.redo); if (button.length > 0) { events = $._data(button[0], 'events'); redoButtonInitialized = true; if (events && events.click && events.click.length > 0) { originalRedo = events.click[0].handler; events.click[0].handler = redo; } else { button.click(redo); } } } if (window.kelmu.data[id].settings.undo && !undoButtonInitialized) { button = element.find(window.kelmu.data[id].settings.undo); if (button.length > 0) { events = $._data(button[0], 'events'); undoButtonInitialized = true; if (events && events.click && events.click.length > 0) { originalUndo = events.click[0].handler; events.click[0].handler = undo; } else { button.click(undo); } } } if (window.kelmu.data[id].settings.begin && !beginButtonInitialized) { button = element.find(window.kelmu.data[id].settings.begin); if (button.length > 0) { events = $._data(button[0], 'events'); beginButtonInitialized = true; if (events && events.click && events.click.length > 0) { originalBegin = events.click[0].handler; events.click[0].handler = begin; } else { button.click(begin); } } } }
[ "function", "(", ")", "{", "var", "events", ";", "var", "button", ";", "if", "(", "window", ".", "kelmu", ".", "data", "[", "id", "]", ".", "settings", ".", "step", "&&", "!", "stepButtonInitialized", ")", "{", "button", "=", "element", ".", "find", "(", "window", ".", "kelmu", ".", "data", "[", "id", "]", ".", "settings", ".", "step", ")", ";", "if", "(", "button", ".", "length", ">", "0", ")", "{", "events", "=", "$", ".", "_data", "(", "button", "[", "0", "]", ",", "'events'", ")", ";", "stepButtonInitialized", "=", "true", ";", "if", "(", "events", "&&", "events", ".", "click", "&&", "events", ".", "click", ".", "length", ">", "0", ")", "{", "originalStep", "=", "events", ".", "click", "[", "0", "]", ".", "handler", ";", "events", ".", "click", "[", "0", "]", ".", "handler", "=", "forwardAndSkip", ";", "}", "else", "{", "button", ".", "click", "(", "forwardAndSkip", ")", ";", "}", "}", "}", "if", "(", "window", ".", "kelmu", ".", "data", "[", "id", "]", ".", "settings", ".", "redo", "&&", "!", "redoButtonInitialized", ")", "{", "button", "=", "element", ".", "find", "(", "window", ".", "kelmu", ".", "data", "[", "id", "]", ".", "settings", ".", "redo", ")", ";", "if", "(", "button", ".", "length", ">", "0", ")", "{", "events", "=", "$", ".", "_data", "(", "button", "[", "0", "]", ",", "'events'", ")", ";", "redoButtonInitialized", "=", "true", ";", "if", "(", "events", "&&", "events", ".", "click", "&&", "events", ".", "click", ".", "length", ">", "0", ")", "{", "originalRedo", "=", "events", ".", "click", "[", "0", "]", ".", "handler", ";", "events", ".", "click", "[", "0", "]", ".", "handler", "=", "redo", ";", "}", "else", "{", "button", ".", "click", "(", "redo", ")", ";", "}", "}", "}", "if", "(", "window", ".", "kelmu", ".", "data", "[", "id", "]", ".", "settings", ".", "undo", "&&", "!", "undoButtonInitialized", ")", "{", "button", "=", "element", ".", "find", "(", "window", ".", "kelmu", ".", "data", "[", "id", "]", ".", "settings", ".", "undo", ")", ";", "if", "(", "button", ".", "length", ">", "0", ")", "{", "events", "=", "$", ".", "_data", "(", "button", "[", "0", "]", ",", "'events'", ")", ";", "undoButtonInitialized", "=", "true", ";", "if", "(", "events", "&&", "events", ".", "click", "&&", "events", ".", "click", ".", "length", ">", "0", ")", "{", "originalUndo", "=", "events", ".", "click", "[", "0", "]", ".", "handler", ";", "events", ".", "click", "[", "0", "]", ".", "handler", "=", "undo", ";", "}", "else", "{", "button", ".", "click", "(", "undo", ")", ";", "}", "}", "}", "if", "(", "window", ".", "kelmu", ".", "data", "[", "id", "]", ".", "settings", ".", "begin", "&&", "!", "beginButtonInitialized", ")", "{", "button", "=", "element", ".", "find", "(", "window", ".", "kelmu", ".", "data", "[", "id", "]", ".", "settings", ".", "begin", ")", ";", "if", "(", "button", ".", "length", ">", "0", ")", "{", "events", "=", "$", ".", "_data", "(", "button", "[", "0", "]", ",", "'events'", ")", ";", "beginButtonInitialized", "=", "true", ";", "if", "(", "events", "&&", "events", ".", "click", "&&", "events", ".", "click", ".", "length", ">", "0", ")", "{", "originalBegin", "=", "events", ".", "click", "[", "0", "]", ".", "handler", ";", "events", ".", "click", "[", "0", "]", ".", "handler", "=", "begin", ";", "}", "else", "{", "button", ".", "click", "(", "begin", ")", ";", "}", "}", "}", "}" ]
Initializes the buttons and sets proxies to take over the original click handlers.
[ "Initializes", "the", "buttons", "and", "sets", "proxies", "to", "take", "over", "the", "original", "click", "handlers", "." ]
71105b5b43027c517a1da99d6cb0a7687fe253b9
https://github.com/acos-server/acos-kelmu/blob/71105b5b43027c517a1da99d6cb0a7687fe253b9/static/kelmu.js#L271-L336
train
acos-server/acos-kelmu
static/kelmu.js
function(event, action) { var data = window.kelmu.data[id]; var stepsLeft = Math.max(+(action.parameter || 1), 1); var stepsToRun = 0; var proceed = function() { this('skip', stepsToRun); }; while (stepsLeft > 0) { var subSteps = (data.definitions['step' + data.stepNumber] || [null]).length - 1; var currentSub = data.subStepNumber; var canIncrease = subSteps - currentSub; if (canIncrease < stepsLeft) { data.stepNumber += 1; data.subStepNumber = 0; stepsToRun += 1; stepsLeft -= canIncrease + 1; } else if (canIncrease > 0) { if (stepsToRun > 0) { $.each(window.kelmu.callbacks[id], proceed); stepsToRun = 0; clearAnnotations(); originalStep(event); } stepsLeft -= canIncrease; data.subStepNumber = data.subStepNumber + canIncrease; } else { data.stepNumber += 1; stepsToRun += 1; stepsLeft -= 1; } } if (stepsToRun > 0) { $.each(window.kelmu.callbacks[id], proceed); stepsToRun = 0; clearAnnotations(); originalStep(event); if (!window.kelmu.data[id].animationReadyAvailable) { setTimeout(function() { createAnnotations(); if (window.kelmu.data[id].actions.updateEditor) { window.kelmu.data[id].actions.updateEditor(); } }, window.kelmu.data[id].settings.animationLength); } } else { createAnnotations(); } window.kelmu.data[id].undoStack.splice(window.kelmu.data[id].undoStackPointer + 1, window.kelmu.data[id].undoStack.length); window.kelmu.data[id].undoStack.push([window.kelmu.data[id].stepNumber, window.kelmu.data[id].subStepNumber]); window.kelmu.data[id].undoStackPointer += 1; }
javascript
function(event, action) { var data = window.kelmu.data[id]; var stepsLeft = Math.max(+(action.parameter || 1), 1); var stepsToRun = 0; var proceed = function() { this('skip', stepsToRun); }; while (stepsLeft > 0) { var subSteps = (data.definitions['step' + data.stepNumber] || [null]).length - 1; var currentSub = data.subStepNumber; var canIncrease = subSteps - currentSub; if (canIncrease < stepsLeft) { data.stepNumber += 1; data.subStepNumber = 0; stepsToRun += 1; stepsLeft -= canIncrease + 1; } else if (canIncrease > 0) { if (stepsToRun > 0) { $.each(window.kelmu.callbacks[id], proceed); stepsToRun = 0; clearAnnotations(); originalStep(event); } stepsLeft -= canIncrease; data.subStepNumber = data.subStepNumber + canIncrease; } else { data.stepNumber += 1; stepsToRun += 1; stepsLeft -= 1; } } if (stepsToRun > 0) { $.each(window.kelmu.callbacks[id], proceed); stepsToRun = 0; clearAnnotations(); originalStep(event); if (!window.kelmu.data[id].animationReadyAvailable) { setTimeout(function() { createAnnotations(); if (window.kelmu.data[id].actions.updateEditor) { window.kelmu.data[id].actions.updateEditor(); } }, window.kelmu.data[id].settings.animationLength); } } else { createAnnotations(); } window.kelmu.data[id].undoStack.splice(window.kelmu.data[id].undoStackPointer + 1, window.kelmu.data[id].undoStack.length); window.kelmu.data[id].undoStack.push([window.kelmu.data[id].stepNumber, window.kelmu.data[id].subStepNumber]); window.kelmu.data[id].undoStackPointer += 1; }
[ "function", "(", "event", ",", "action", ")", "{", "var", "data", "=", "window", ".", "kelmu", ".", "data", "[", "id", "]", ";", "var", "stepsLeft", "=", "Math", ".", "max", "(", "+", "(", "action", ".", "parameter", "||", "1", ")", ",", "1", ")", ";", "var", "stepsToRun", "=", "0", ";", "var", "proceed", "=", "function", "(", ")", "{", "this", "(", "'skip'", ",", "stepsToRun", ")", ";", "}", ";", "while", "(", "stepsLeft", ">", "0", ")", "{", "var", "subSteps", "=", "(", "data", ".", "definitions", "[", "'step'", "+", "data", ".", "stepNumber", "]", "||", "[", "null", "]", ")", ".", "length", "-", "1", ";", "var", "currentSub", "=", "data", ".", "subStepNumber", ";", "var", "canIncrease", "=", "subSteps", "-", "currentSub", ";", "if", "(", "canIncrease", "<", "stepsLeft", ")", "{", "data", ".", "stepNumber", "+=", "1", ";", "data", ".", "subStepNumber", "=", "0", ";", "stepsToRun", "+=", "1", ";", "stepsLeft", "-=", "canIncrease", "+", "1", ";", "}", "else", "if", "(", "canIncrease", ">", "0", ")", "{", "if", "(", "stepsToRun", ">", "0", ")", "{", "$", ".", "each", "(", "window", ".", "kelmu", ".", "callbacks", "[", "id", "]", ",", "proceed", ")", ";", "stepsToRun", "=", "0", ";", "clearAnnotations", "(", ")", ";", "originalStep", "(", "event", ")", ";", "}", "stepsLeft", "-=", "canIncrease", ";", "data", ".", "subStepNumber", "=", "data", ".", "subStepNumber", "+", "canIncrease", ";", "}", "else", "{", "data", ".", "stepNumber", "+=", "1", ";", "stepsToRun", "+=", "1", ";", "stepsLeft", "-=", "1", ";", "}", "}", "if", "(", "stepsToRun", ">", "0", ")", "{", "$", ".", "each", "(", "window", ".", "kelmu", ".", "callbacks", "[", "id", "]", ",", "proceed", ")", ";", "stepsToRun", "=", "0", ";", "clearAnnotations", "(", ")", ";", "originalStep", "(", "event", ")", ";", "if", "(", "!", "window", ".", "kelmu", ".", "data", "[", "id", "]", ".", "animationReadyAvailable", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "createAnnotations", "(", ")", ";", "if", "(", "window", ".", "kelmu", ".", "data", "[", "id", "]", ".", "actions", ".", "updateEditor", ")", "{", "window", ".", "kelmu", ".", "data", "[", "id", "]", ".", "actions", ".", "updateEditor", "(", ")", ";", "}", "}", ",", "window", ".", "kelmu", ".", "data", "[", "id", "]", ".", "settings", ".", "animationLength", ")", ";", "}", "}", "else", "{", "createAnnotations", "(", ")", ";", "}", "window", ".", "kelmu", ".", "data", "[", "id", "]", ".", "undoStack", ".", "splice", "(", "window", ".", "kelmu", ".", "data", "[", "id", "]", ".", "undoStackPointer", "+", "1", ",", "window", ".", "kelmu", ".", "data", "[", "id", "]", ".", "undoStack", ".", "length", ")", ";", "window", ".", "kelmu", ".", "data", "[", "id", "]", ".", "undoStack", ".", "push", "(", "[", "window", ".", "kelmu", ".", "data", "[", "id", "]", ".", "stepNumber", ",", "window", ".", "kelmu", ".", "data", "[", "id", "]", ".", "subStepNumber", "]", ")", ";", "window", ".", "kelmu", ".", "data", "[", "id", "]", ".", "undoStackPointer", "+=", "1", ";", "}" ]
Functionality for the `skip` action.
[ "Functionality", "for", "the", "skip", "action", "." ]
71105b5b43027c517a1da99d6cb0a7687fe253b9
https://github.com/acos-server/acos-kelmu/blob/71105b5b43027c517a1da99d6cb0a7687fe253b9/static/kelmu.js#L341-L405
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/wysiwygarea/plugin.js
blockResizeStart
function blockResizeStart() { var lastListeningElement; // We'll attach only one listener at a time, instead of adding it to every img, input, hr etc. // Listener will be attached upon selectionChange, we'll also check if there was any element that // got listener before (lastListeningElement) - if so we need to remove previous listener. editor.editable().attachListener( editor, 'selectionChange', function() { var selectedElement = editor.getSelection().getSelectedElement(); if ( selectedElement ) { if ( lastListeningElement ) { lastListeningElement.detachEvent( 'onresizestart', resizeStartListener ); lastListeningElement = null; } // IE requires using attachEvent, because it does not work using W3C compilant addEventListener, // tested with IE10. selectedElement.$.attachEvent( 'onresizestart', resizeStartListener ); lastListeningElement = selectedElement.$; } } ); }
javascript
function blockResizeStart() { var lastListeningElement; // We'll attach only one listener at a time, instead of adding it to every img, input, hr etc. // Listener will be attached upon selectionChange, we'll also check if there was any element that // got listener before (lastListeningElement) - if so we need to remove previous listener. editor.editable().attachListener( editor, 'selectionChange', function() { var selectedElement = editor.getSelection().getSelectedElement(); if ( selectedElement ) { if ( lastListeningElement ) { lastListeningElement.detachEvent( 'onresizestart', resizeStartListener ); lastListeningElement = null; } // IE requires using attachEvent, because it does not work using W3C compilant addEventListener, // tested with IE10. selectedElement.$.attachEvent( 'onresizestart', resizeStartListener ); lastListeningElement = selectedElement.$; } } ); }
[ "function", "blockResizeStart", "(", ")", "{", "var", "lastListeningElement", ";", "editor", ".", "editable", "(", ")", ".", "attachListener", "(", "editor", ",", "'selectionChange'", ",", "function", "(", ")", "{", "var", "selectedElement", "=", "editor", ".", "getSelection", "(", ")", ".", "getSelectedElement", "(", ")", ";", "if", "(", "selectedElement", ")", "{", "if", "(", "lastListeningElement", ")", "{", "lastListeningElement", ".", "detachEvent", "(", "'onresizestart'", ",", "resizeStartListener", ")", ";", "lastListeningElement", "=", "null", ";", "}", "selectedElement", ".", "$", ".", "attachEvent", "(", "'onresizestart'", ",", "resizeStartListener", ")", ";", "lastListeningElement", "=", "selectedElement", ".", "$", ";", "}", "}", ")", ";", "}" ]
Disables resizing by preventing default action on resizestart event.
[ "Disables", "resizing", "by", "preventing", "default", "action", "on", "resizestart", "event", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/wysiwygarea/plugin.js#L569-L590
train
david4096/ga4gh-node-gateway
src/router.js
expressGetHandler
function expressGetHandler(endpoint) { return function(req, res) { // We have to handle request parameters differently since they're not in the // request body. rpc.getMethod(endpoint.name)({request: req.params}, function(err, doc) { res.send(doc); res.end(); }); }; }
javascript
function expressGetHandler(endpoint) { return function(req, res) { // We have to handle request parameters differently since they're not in the // request body. rpc.getMethod(endpoint.name)({request: req.params}, function(err, doc) { res.send(doc); res.end(); }); }; }
[ "function", "expressGetHandler", "(", "endpoint", ")", "{", "return", "function", "(", "req", ",", "res", ")", "{", "rpc", ".", "getMethod", "(", "endpoint", ".", "name", ")", "(", "{", "request", ":", "req", ".", "params", "}", ",", "function", "(", "err", ",", "doc", ")", "{", "res", ".", "send", "(", "doc", ")", ";", "res", ".", "end", "(", ")", ";", "}", ")", ";", "}", ";", "}" ]
Returns a callback that will be sent to the controller function when a GET endpoint is requested.
[ "Returns", "a", "callback", "that", "will", "be", "sent", "to", "the", "controller", "function", "when", "a", "GET", "endpoint", "is", "requested", "." ]
3864c10503c9273ea2697d1754bef775ec6ad536
https://github.com/david4096/ga4gh-node-gateway/blob/3864c10503c9273ea2697d1754bef775ec6ad536/src/router.js#L28-L37
train
tunnckoCore/load-deps
index.js
req
function req (name, opts) { if (opts && opts.require) { return opts.require(name, opts) } var fp = require.resolve(name) return require(fp) }
javascript
function req (name, opts) { if (opts && opts.require) { return opts.require(name, opts) } var fp = require.resolve(name) return require(fp) }
[ "function", "req", "(", "name", ",", "opts", ")", "{", "if", "(", "opts", "&&", "opts", ".", "require", ")", "{", "return", "opts", ".", "require", "(", "name", ",", "opts", ")", "}", "var", "fp", "=", "require", ".", "resolve", "(", "name", ")", "return", "require", "(", "fp", ")", "}" ]
Default `require` function. Pass a custom function to `opts.require` to override. @param {String} `name` @param {Object} `opts` @return {String}
[ "Default", "require", "function", ".", "Pass", "a", "custom", "function", "to", "opts", ".", "require", "to", "override", "." ]
ddf4f81c06664fc0d6ff3bb87aa942f3be0ee2e0
https://github.com/tunnckoCore/load-deps/blob/ddf4f81c06664fc0d6ff3bb87aa942f3be0ee2e0/index.js#L81-L87
train
tunnckoCore/load-deps
index.js
renameKey
function renameKey (name, opts) { if (opts && opts.renameKey) { return opts.renameKey(name, opts) } return name }
javascript
function renameKey (name, opts) { if (opts && opts.renameKey) { return opts.renameKey(name, opts) } return name }
[ "function", "renameKey", "(", "name", ",", "opts", ")", "{", "if", "(", "opts", "&&", "opts", ".", "renameKey", ")", "{", "return", "opts", ".", "renameKey", "(", "name", ",", "opts", ")", "}", "return", "name", "}" ]
Default `renameKey` function. Pass a custom function to `opts.renameKey` to override. @param {String} `name` @param {Object} `opts` @return {String}
[ "Default", "renameKey", "function", ".", "Pass", "a", "custom", "function", "to", "opts", ".", "renameKey", "to", "override", "." ]
ddf4f81c06664fc0d6ff3bb87aa942f3be0ee2e0
https://github.com/tunnckoCore/load-deps/blob/ddf4f81c06664fc0d6ff3bb87aa942f3be0ee2e0/index.js#L97-L102
train
mobkits/tap-event
index.js
cleanup
function cleanup(e2) { // if it's the same event as the origin, // then don't actually cleanup. // hit issues with this - don't remember if (e1 === e2) return clearTimeout(timeout_id) el.removeEventListener('touchmove', cleanup) endEvents.forEach(function (event) { el.removeEventListener(event, done) }) }
javascript
function cleanup(e2) { // if it's the same event as the origin, // then don't actually cleanup. // hit issues with this - don't remember if (e1 === e2) return clearTimeout(timeout_id) el.removeEventListener('touchmove', cleanup) endEvents.forEach(function (event) { el.removeEventListener(event, done) }) }
[ "function", "cleanup", "(", "e2", ")", "{", "if", "(", "e1", "===", "e2", ")", "return", "clearTimeout", "(", "timeout_id", ")", "el", ".", "removeEventListener", "(", "'touchmove'", ",", "cleanup", ")", "endEvents", ".", "forEach", "(", "function", "(", "event", ")", "{", "el", ".", "removeEventListener", "(", "event", ",", "done", ")", "}", ")", "}" ]
cleanup end events to cancel the tap, just run this early
[ "cleanup", "end", "events", "to", "cancel", "the", "tap", "just", "run", "this", "early" ]
f8d7a4a2db607bed162b7697e5c9daa2097e0a61
https://github.com/mobkits/tap-event/blob/f8d7a4a2db607bed162b7697e5c9daa2097e0a61/index.js#L72-L85
train
stdarg/async-err
index.js
asyncerr
function asyncerr(err, cb) { if (!util.isError(err, Error)) return debug(BAD_ERR_ERR); if (typeof err.message === 'string' && err.message.length) debug(err.message); if (typeof err.stack === 'object') debug(err.stack); if (!is.func(cb)) return debug(BAD_CB_ERR+util.inspect(cb)); // call the callback on the next tick of the event loop process.nextTick(function() { cb(err); }); }
javascript
function asyncerr(err, cb) { if (!util.isError(err, Error)) return debug(BAD_ERR_ERR); if (typeof err.message === 'string' && err.message.length) debug(err.message); if (typeof err.stack === 'object') debug(err.stack); if (!is.func(cb)) return debug(BAD_CB_ERR+util.inspect(cb)); // call the callback on the next tick of the event loop process.nextTick(function() { cb(err); }); }
[ "function", "asyncerr", "(", "err", ",", "cb", ")", "{", "if", "(", "!", "util", ".", "isError", "(", "err", ",", "Error", ")", ")", "return", "debug", "(", "BAD_ERR_ERR", ")", ";", "if", "(", "typeof", "err", ".", "message", "===", "'string'", "&&", "err", ".", "message", ".", "length", ")", "debug", "(", "err", ".", "message", ")", ";", "if", "(", "typeof", "err", ".", "stack", "===", "'object'", ")", "debug", "(", "err", ".", "stack", ")", ";", "if", "(", "!", "is", ".", "func", "(", "cb", ")", ")", "return", "debug", "(", "BAD_CB_ERR", "+", "util", ".", "inspect", "(", "cb", ")", ")", ";", "process", ".", "nextTick", "(", "function", "(", ")", "{", "cb", "(", "err", ")", ";", "}", ")", ";", "}" ]
A convenience function to make otherwise sync errors async. If you give asyncerr incorrect arguments, it will send messages to the console via the debug module, but that's it. @param {Object} err A Node.js Error object. @param {Function} cb A function object as callback.
[ "A", "convenience", "function", "to", "make", "otherwise", "sync", "errors", "async", ".", "If", "you", "give", "asyncerr", "incorrect", "arguments", "it", "will", "send", "messages", "to", "the", "console", "via", "the", "debug", "module", "but", "that", "s", "it", "." ]
36ada42c92963f5a6648e9463b3e4767875437e1
https://github.com/stdarg/async-err/blob/36ada42c92963f5a6648e9463b3e4767875437e1/index.js#L19-L36
train
douglasduteil/ngdoc-parser
lib/DocCommentParser.js
DocCommentParser
function DocCommentParser(text) { this.lines = text.split(END_OF_LINE); this.lineNumber = 0; this.length = this.lines.length; this.line = ''; this.match = []; this.tagDef = {}; this.mode = this._extractLine; this.data = {}; }
javascript
function DocCommentParser(text) { this.lines = text.split(END_OF_LINE); this.lineNumber = 0; this.length = this.lines.length; this.line = ''; this.match = []; this.tagDef = {}; this.mode = this._extractLine; this.data = {}; }
[ "function", "DocCommentParser", "(", "text", ")", "{", "this", ".", "lines", "=", "text", ".", "split", "(", "END_OF_LINE", ")", ";", "this", ".", "lineNumber", "=", "0", ";", "this", ".", "length", "=", "this", ".", "lines", ".", "length", ";", "this", ".", "line", "=", "''", ";", "this", ".", "match", "=", "[", "]", ";", "this", ".", "tagDef", "=", "{", "}", ";", "this", ".", "mode", "=", "this", ".", "_extractLine", ";", "this", ".", "data", "=", "{", "}", ";", "}" ]
A little doc parser to extract inline or multiline comments @alias module:DocCommentParser @param {string} text The text to parse. @constructor
[ "A", "little", "doc", "parser", "to", "extract", "inline", "or", "multiline", "comments" ]
9fc11adb71cd260f8d67f6fd34b907ba92e3ecbb
https://github.com/douglasduteil/ngdoc-parser/blob/9fc11adb71cd260f8d67f6fd34b907ba92e3ecbb/lib/DocCommentParser.js#L22-L34
train
IonicaBizau/diable
lib/index.js
Diable
function Diable(opts) { // The process is a daemon if (Diable.isDaemon()) { return false } opts = opts || {} const args = [].concat(process.argv) args.shift() const script = args.shift() , env = opts.env || process.env Diable.daemonize(script, args, opts) return process.exit() }
javascript
function Diable(opts) { // The process is a daemon if (Diable.isDaemon()) { return false } opts = opts || {} const args = [].concat(process.argv) args.shift() const script = args.shift() , env = opts.env || process.env Diable.daemonize(script, args, opts) return process.exit() }
[ "function", "Diable", "(", "opts", ")", "{", "if", "(", "Diable", ".", "isDaemon", "(", ")", ")", "{", "return", "false", "}", "opts", "=", "opts", "||", "{", "}", "const", "args", "=", "[", "]", ".", "concat", "(", "process", ".", "argv", ")", "args", ".", "shift", "(", ")", "const", "script", "=", "args", ".", "shift", "(", ")", ",", "env", "=", "opts", ".", "env", "||", "process", ".", "env", "Diable", ".", "daemonize", "(", "script", ",", "args", ",", "opts", ")", "return", "process", ".", "exit", "(", ")", "}" ]
Diable Daemonizes processes the current process. @name Diable @function @param {Object} opts An object which will be passed to the `exec` function. It is extended with: - `env` (Object): The environment object (default: `process.env`). @return {Number|Process} `false` if the process was already daemonized. Otherwise the process is closed anyways.
[ "Diable", "Daemonizes", "processes", "the", "current", "process", "." ]
dddf7ef19b233a3f4c0e464b4f9e689f7f64d351
https://github.com/IonicaBizau/diable/blob/dddf7ef19b233a3f4c0e464b4f9e689f7f64d351/lib/index.js#L17-L34
train
gummesson/markdown-stream
index.js
markdown
function markdown(preset, options) { var stream = through(transform, flush) var parser = new Remarkable(preset, options) var buffer = [] function transform(chunk, encoding, done) { buffer.push(chunk) done() } function flush(done) { this.push(parser.render(buffer.join('\n'))) done() } return stream }
javascript
function markdown(preset, options) { var stream = through(transform, flush) var parser = new Remarkable(preset, options) var buffer = [] function transform(chunk, encoding, done) { buffer.push(chunk) done() } function flush(done) { this.push(parser.render(buffer.join('\n'))) done() } return stream }
[ "function", "markdown", "(", "preset", ",", "options", ")", "{", "var", "stream", "=", "through", "(", "transform", ",", "flush", ")", "var", "parser", "=", "new", "Remarkable", "(", "preset", ",", "options", ")", "var", "buffer", "=", "[", "]", "function", "transform", "(", "chunk", ",", "encoding", ",", "done", ")", "{", "buffer", ".", "push", "(", "chunk", ")", "done", "(", ")", "}", "function", "flush", "(", "done", ")", "{", "this", ".", "push", "(", "parser", ".", "render", "(", "buffer", ".", "join", "(", "'\\n'", ")", ")", ")", "\\n", "}", "done", "(", ")", "}" ]
Tranform a stream of Markdown into HTML. @param {string} [preset] @param {object} [options] @return {object} @api public
[ "Tranform", "a", "stream", "of", "Markdown", "into", "HTML", "." ]
1841c046b96cb82fe1ad080f5f429c3c386c8f33
https://github.com/gummesson/markdown-stream/blob/1841c046b96cb82fe1ad080f5f429c3c386c8f33/index.js#L18-L34
train
gaiajs/gaiajs
lib/config/index.js
getFileContent
function getFileContent(ext, file) { var conf = {}; switch (ext) { case '.js': conf = require(file); break; case '.json': conf = JSON.parse(fs.readFileSync(file, { encoding: 'utf-8' })); break; case '.yml': conf = yaml.safeLoad(fs.readFileSync(file, { encoding: 'utf-8' })); break; } return conf; }
javascript
function getFileContent(ext, file) { var conf = {}; switch (ext) { case '.js': conf = require(file); break; case '.json': conf = JSON.parse(fs.readFileSync(file, { encoding: 'utf-8' })); break; case '.yml': conf = yaml.safeLoad(fs.readFileSync(file, { encoding: 'utf-8' })); break; } return conf; }
[ "function", "getFileContent", "(", "ext", ",", "file", ")", "{", "var", "conf", "=", "{", "}", ";", "switch", "(", "ext", ")", "{", "case", "'.js'", ":", "conf", "=", "require", "(", "file", ")", ";", "break", ";", "case", "'.json'", ":", "conf", "=", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "file", ",", "{", "encoding", ":", "'utf-8'", "}", ")", ")", ";", "break", ";", "case", "'.yml'", ":", "conf", "=", "yaml", ".", "safeLoad", "(", "fs", ".", "readFileSync", "(", "file", ",", "{", "encoding", ":", "'utf-8'", "}", ")", ")", ";", "break", ";", "}", "return", "conf", ";", "}" ]
Get file content
[ "Get", "file", "content" ]
a8ebc50274b83bed8bed007e691761bdc3b52eaa
https://github.com/gaiajs/gaiajs/blob/a8ebc50274b83bed8bed007e691761bdc3b52eaa/lib/config/index.js#L145-L164
train
seriousManual/node-depugger
index.js
depugger
function depugger(pDebug, pName) { var debug, name, backend; if (typeof pDebug === 'object') { debug = !!pDebug.debug; name = pDebug.name || ''; backend = pDebug.backend || stdBackend; } else { debug = !!pDebug; name = pName || ''; backend = stdBackend; } var prefix = name ? util.format('[%s] ', name) : ''; var logFunction = function() { var args = Array.prototype.splice.call(arguments, 0); var message = util.format.apply(null, args); message = prefix + message; backend.write(message); }; if(!debug) { logFunction = noop; } logFunction.child = function(childName) { var newName = name ? name + '.' + childName : childName; return depugger({debug: debug, name: newName, backend: backend}); }; return logFunction; }
javascript
function depugger(pDebug, pName) { var debug, name, backend; if (typeof pDebug === 'object') { debug = !!pDebug.debug; name = pDebug.name || ''; backend = pDebug.backend || stdBackend; } else { debug = !!pDebug; name = pName || ''; backend = stdBackend; } var prefix = name ? util.format('[%s] ', name) : ''; var logFunction = function() { var args = Array.prototype.splice.call(arguments, 0); var message = util.format.apply(null, args); message = prefix + message; backend.write(message); }; if(!debug) { logFunction = noop; } logFunction.child = function(childName) { var newName = name ? name + '.' + childName : childName; return depugger({debug: debug, name: newName, backend: backend}); }; return logFunction; }
[ "function", "depugger", "(", "pDebug", ",", "pName", ")", "{", "var", "debug", ",", "name", ",", "backend", ";", "if", "(", "typeof", "pDebug", "===", "'object'", ")", "{", "debug", "=", "!", "!", "pDebug", ".", "debug", ";", "name", "=", "pDebug", ".", "name", "||", "''", ";", "backend", "=", "pDebug", ".", "backend", "||", "stdBackend", ";", "}", "else", "{", "debug", "=", "!", "!", "pDebug", ";", "name", "=", "pName", "||", "''", ";", "backend", "=", "stdBackend", ";", "}", "var", "prefix", "=", "name", "?", "util", ".", "format", "(", "'[%s] '", ",", "name", ")", ":", "''", ";", "var", "logFunction", "=", "function", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "splice", ".", "call", "(", "arguments", ",", "0", ")", ";", "var", "message", "=", "util", ".", "format", ".", "apply", "(", "null", ",", "args", ")", ";", "message", "=", "prefix", "+", "message", ";", "backend", ".", "write", "(", "message", ")", ";", "}", ";", "if", "(", "!", "debug", ")", "{", "logFunction", "=", "noop", ";", "}", "logFunction", ".", "child", "=", "function", "(", "childName", ")", "{", "var", "newName", "=", "name", "?", "name", "+", "'.'", "+", "childName", ":", "childName", ";", "return", "depugger", "(", "{", "debug", ":", "debug", ",", "name", ":", "newName", ",", "backend", ":", "backend", "}", ")", ";", "}", ";", "return", "logFunction", ";", "}" ]
returns a a function that is used to create debug messages the logging of the messages happens in the context of the initializing factory method @param pDebug flag that indicates if debugging should be activated @param pName context name for debugging messages @return {Function}
[ "returns", "a", "a", "function", "that", "is", "used", "to", "create", "debug", "messages", "the", "logging", "of", "the", "messages", "happens", "in", "the", "context", "of", "the", "initializing", "factory", "method" ]
3568fd546f8674ade271361de38e1d5374ff2ce6
https://github.com/seriousManual/node-depugger/blob/3568fd546f8674ade271361de38e1d5374ff2ce6/index.js#L15-L49
train
kudla/react-declaration-loader
lib/traverse.js
traverse
function traverse(ast) { var visitors = flatten(slice.call(arguments, 1)); estraverse.traverse(ast, { enter: function(node) { var type = node.type; var methodName = type + 'Enter'; visitorsCall('enter', this, arguments); visitorsCall(methodName, this, arguments); }, leave: function(node) { var type = node.type; var methodName = type + 'Leave'; visitorsCall('leave', this, arguments); visitorsCall(methodName, this, arguments); } }); function visitorsCall(methodName, context, args) { var callArgs = slice.call(args); var callBreak; var visitorContext = Object.assign( Object.create(context), { skip: function() { callBreak = true; context.skip(); }, break: function() { callBreak = true; context.break(); } } ); visitors.some(function(visitor) { var method = visitor[methodName]; if (method) { method.apply(visitorContext, callArgs); } return callBreak; }); } }
javascript
function traverse(ast) { var visitors = flatten(slice.call(arguments, 1)); estraverse.traverse(ast, { enter: function(node) { var type = node.type; var methodName = type + 'Enter'; visitorsCall('enter', this, arguments); visitorsCall(methodName, this, arguments); }, leave: function(node) { var type = node.type; var methodName = type + 'Leave'; visitorsCall('leave', this, arguments); visitorsCall(methodName, this, arguments); } }); function visitorsCall(methodName, context, args) { var callArgs = slice.call(args); var callBreak; var visitorContext = Object.assign( Object.create(context), { skip: function() { callBreak = true; context.skip(); }, break: function() { callBreak = true; context.break(); } } ); visitors.some(function(visitor) { var method = visitor[methodName]; if (method) { method.apply(visitorContext, callArgs); } return callBreak; }); } }
[ "function", "traverse", "(", "ast", ")", "{", "var", "visitors", "=", "flatten", "(", "slice", ".", "call", "(", "arguments", ",", "1", ")", ")", ";", "estraverse", ".", "traverse", "(", "ast", ",", "{", "enter", ":", "function", "(", "node", ")", "{", "var", "type", "=", "node", ".", "type", ";", "var", "methodName", "=", "type", "+", "'Enter'", ";", "visitorsCall", "(", "'enter'", ",", "this", ",", "arguments", ")", ";", "visitorsCall", "(", "methodName", ",", "this", ",", "arguments", ")", ";", "}", ",", "leave", ":", "function", "(", "node", ")", "{", "var", "type", "=", "node", ".", "type", ";", "var", "methodName", "=", "type", "+", "'Leave'", ";", "visitorsCall", "(", "'leave'", ",", "this", ",", "arguments", ")", ";", "visitorsCall", "(", "methodName", ",", "this", ",", "arguments", ")", ";", "}", "}", ")", ";", "function", "visitorsCall", "(", "methodName", ",", "context", ",", "args", ")", "{", "var", "callArgs", "=", "slice", ".", "call", "(", "args", ")", ";", "var", "callBreak", ";", "var", "visitorContext", "=", "Object", ".", "assign", "(", "Object", ".", "create", "(", "context", ")", ",", "{", "skip", ":", "function", "(", ")", "{", "callBreak", "=", "true", ";", "context", ".", "skip", "(", ")", ";", "}", ",", "break", ":", "function", "(", ")", "{", "callBreak", "=", "true", ";", "context", ".", "break", "(", ")", ";", "}", "}", ")", ";", "visitors", ".", "some", "(", "function", "(", "visitor", ")", "{", "var", "method", "=", "visitor", "[", "methodName", "]", ";", "if", "(", "method", ")", "{", "method", ".", "apply", "(", "visitorContext", ",", "callArgs", ")", ";", "}", "return", "callBreak", ";", "}", ")", ";", "}", "}" ]
traverse - AST traverse helper @param {AST} ast @param {Object} ...visitors hash of visitor functions
[ "traverse", "-", "AST", "traverse", "helper" ]
50f430a49cffc99a8188648452d3740cbef49c1c
https://github.com/kudla/react-declaration-loader/blob/50f430a49cffc99a8188648452d3740cbef49c1c/lib/traverse.js#L14-L57
train
andrepolischuk/eventhash
index.js
fix
function fix(fn, path) { if (!running) return; if (path !== location.hash) { fn(); path = location.hash; } setTimeout(function() { fix(fn, path); }, 500); }
javascript
function fix(fn, path) { if (!running) return; if (path !== location.hash) { fn(); path = location.hash; } setTimeout(function() { fix(fn, path); }, 500); }
[ "function", "fix", "(", "fn", ",", "path", ")", "{", "if", "(", "!", "running", ")", "return", ";", "if", "(", "path", "!==", "location", ".", "hash", ")", "{", "fn", "(", ")", ";", "path", "=", "location", ".", "hash", ";", "}", "setTimeout", "(", "function", "(", ")", "{", "fix", "(", "fn", ",", "path", ")", ";", "}", ",", "500", ")", ";", "}" ]
onhashchange fix for IE<8 @param {Function} fn @param {String} path @api private
[ "onhashchange", "fix", "for", "IE<8" ]
b34584acd7cae3e40c1f55e50a0a5b1dd321a031
https://github.com/andrepolischuk/eventhash/blob/b34584acd7cae3e40c1f55e50a0a5b1dd321a031/index.js#L65-L76
train
sciolist/pellets
browser/pellets.js
parseContinueStatement
function parseContinueStatement() { var token, label = null; expectKeyword('continue'); // Optimize the most common form: 'continue;'. if (source[index] === ';') { lex(); if (!inIteration) { throwError({}, Messages.IllegalContinue); } return { type: Syntax.ContinueStatement, label: null }; } if (peekLineTerminator()) { if (!inIteration) { throwError({}, Messages.IllegalContinue); } return { type: Syntax.ContinueStatement, label: null }; } token = lookahead(); if (token.type === Token.Identifier) { label = parseVariableIdentifier(); if (!Object.prototype.hasOwnProperty.call(labelSet, label.name)) { throwError({}, Messages.UnknownLabel, label.name); } } consumeSemicolon(); if (label === null && !inIteration) { throwError({}, Messages.IllegalContinue); } return { type: Syntax.ContinueStatement, label: label }; }
javascript
function parseContinueStatement() { var token, label = null; expectKeyword('continue'); // Optimize the most common form: 'continue;'. if (source[index] === ';') { lex(); if (!inIteration) { throwError({}, Messages.IllegalContinue); } return { type: Syntax.ContinueStatement, label: null }; } if (peekLineTerminator()) { if (!inIteration) { throwError({}, Messages.IllegalContinue); } return { type: Syntax.ContinueStatement, label: null }; } token = lookahead(); if (token.type === Token.Identifier) { label = parseVariableIdentifier(); if (!Object.prototype.hasOwnProperty.call(labelSet, label.name)) { throwError({}, Messages.UnknownLabel, label.name); } } consumeSemicolon(); if (label === null && !inIteration) { throwError({}, Messages.IllegalContinue); } return { type: Syntax.ContinueStatement, label: label }; }
[ "function", "parseContinueStatement", "(", ")", "{", "var", "token", ",", "label", "=", "null", ";", "expectKeyword", "(", "'continue'", ")", ";", "if", "(", "source", "[", "index", "]", "===", "';'", ")", "{", "lex", "(", ")", ";", "if", "(", "!", "inIteration", ")", "{", "throwError", "(", "{", "}", ",", "Messages", ".", "IllegalContinue", ")", ";", "}", "return", "{", "type", ":", "Syntax", ".", "ContinueStatement", ",", "label", ":", "null", "}", ";", "}", "if", "(", "peekLineTerminator", "(", ")", ")", "{", "if", "(", "!", "inIteration", ")", "{", "throwError", "(", "{", "}", ",", "Messages", ".", "IllegalContinue", ")", ";", "}", "return", "{", "type", ":", "Syntax", ".", "ContinueStatement", ",", "label", ":", "null", "}", ";", "}", "token", "=", "lookahead", "(", ")", ";", "if", "(", "token", ".", "type", "===", "Token", ".", "Identifier", ")", "{", "label", "=", "parseVariableIdentifier", "(", ")", ";", "if", "(", "!", "Object", ".", "prototype", ".", "hasOwnProperty", ".", "call", "(", "labelSet", ",", "label", ".", "name", ")", ")", "{", "throwError", "(", "{", "}", ",", "Messages", ".", "UnknownLabel", ",", "label", ".", "name", ")", ";", "}", "}", "consumeSemicolon", "(", ")", ";", "if", "(", "label", "===", "null", "&&", "!", "inIteration", ")", "{", "throwError", "(", "{", "}", ",", "Messages", ".", "IllegalContinue", ")", ";", "}", "return", "{", "type", ":", "Syntax", ".", "ContinueStatement", ",", "label", ":", "label", "}", ";", "}" ]
12.7 The continue statement
[ "12", ".", "7", "The", "continue", "statement" ]
98ce4b3b9bd0fb4893562d7ba1e121952169cb53
https://github.com/sciolist/pellets/blob/98ce4b3b9bd0fb4893562d7ba1e121952169cb53/browser/pellets.js#L3088-L3137
train
sciolist/pellets
browser/pellets.js
parseReturnStatement
function parseReturnStatement() { var token, argument = null; expectKeyword('return'); if (!inFunctionBody) { throwErrorTolerant({}, Messages.IllegalReturn); } // 'return' followed by a space and an identifier is very common. if (source[index] === ' ') { if (isIdentifierStart(source[index + 1])) { argument = parseExpression(); consumeSemicolon(); return { type: Syntax.ReturnStatement, argument: argument }; } } if (peekLineTerminator()) { return { type: Syntax.ReturnStatement, argument: null }; } if (!match(';')) { token = lookahead(); if (!match('}') && token.type !== Token.EOF) { argument = parseExpression(); } } consumeSemicolon(); return { type: Syntax.ReturnStatement, argument: argument }; }
javascript
function parseReturnStatement() { var token, argument = null; expectKeyword('return'); if (!inFunctionBody) { throwErrorTolerant({}, Messages.IllegalReturn); } // 'return' followed by a space and an identifier is very common. if (source[index] === ' ') { if (isIdentifierStart(source[index + 1])) { argument = parseExpression(); consumeSemicolon(); return { type: Syntax.ReturnStatement, argument: argument }; } } if (peekLineTerminator()) { return { type: Syntax.ReturnStatement, argument: null }; } if (!match(';')) { token = lookahead(); if (!match('}') && token.type !== Token.EOF) { argument = parseExpression(); } } consumeSemicolon(); return { type: Syntax.ReturnStatement, argument: argument }; }
[ "function", "parseReturnStatement", "(", ")", "{", "var", "token", ",", "argument", "=", "null", ";", "expectKeyword", "(", "'return'", ")", ";", "if", "(", "!", "inFunctionBody", ")", "{", "throwErrorTolerant", "(", "{", "}", ",", "Messages", ".", "IllegalReturn", ")", ";", "}", "if", "(", "source", "[", "index", "]", "===", "' '", ")", "{", "if", "(", "isIdentifierStart", "(", "source", "[", "index", "+", "1", "]", ")", ")", "{", "argument", "=", "parseExpression", "(", ")", ";", "consumeSemicolon", "(", ")", ";", "return", "{", "type", ":", "Syntax", ".", "ReturnStatement", ",", "argument", ":", "argument", "}", ";", "}", "}", "if", "(", "peekLineTerminator", "(", ")", ")", "{", "return", "{", "type", ":", "Syntax", ".", "ReturnStatement", ",", "argument", ":", "null", "}", ";", "}", "if", "(", "!", "match", "(", "';'", ")", ")", "{", "token", "=", "lookahead", "(", ")", ";", "if", "(", "!", "match", "(", "'}'", ")", "&&", "token", ".", "type", "!==", "Token", ".", "EOF", ")", "{", "argument", "=", "parseExpression", "(", ")", ";", "}", "}", "consumeSemicolon", "(", ")", ";", "return", "{", "type", ":", "Syntax", ".", "ReturnStatement", ",", "argument", ":", "argument", "}", ";", "}" ]
12.9 The return statement
[ "12", ".", "9", "The", "return", "statement" ]
98ce4b3b9bd0fb4893562d7ba1e121952169cb53
https://github.com/sciolist/pellets/blob/98ce4b3b9bd0fb4893562d7ba1e121952169cb53/browser/pellets.js#L3194-L3235
train
sciolist/pellets
browser/pellets.js
SourceNodeMock
function SourceNodeMock(line, column, filename, chunk) { var result = []; function flatten(input) { var i, iz; if (isArray(input)) { for (i = 0, iz = input.length; i < iz; ++i) { flatten(input[i]); } } else if (input instanceof SourceNodeMock) { result.push(input); } else if (typeof input === 'string' && input) { result.push(input); } } flatten(chunk); this.children = result; }
javascript
function SourceNodeMock(line, column, filename, chunk) { var result = []; function flatten(input) { var i, iz; if (isArray(input)) { for (i = 0, iz = input.length; i < iz; ++i) { flatten(input[i]); } } else if (input instanceof SourceNodeMock) { result.push(input); } else if (typeof input === 'string' && input) { result.push(input); } } flatten(chunk); this.children = result; }
[ "function", "SourceNodeMock", "(", "line", ",", "column", ",", "filename", ",", "chunk", ")", "{", "var", "result", "=", "[", "]", ";", "function", "flatten", "(", "input", ")", "{", "var", "i", ",", "iz", ";", "if", "(", "isArray", "(", "input", ")", ")", "{", "for", "(", "i", "=", "0", ",", "iz", "=", "input", ".", "length", ";", "i", "<", "iz", ";", "++", "i", ")", "{", "flatten", "(", "input", "[", "i", "]", ")", ";", "}", "}", "else", "if", "(", "input", "instanceof", "SourceNodeMock", ")", "{", "result", ".", "push", "(", "input", ")", ";", "}", "else", "if", "(", "typeof", "input", "===", "'string'", "&&", "input", ")", "{", "result", ".", "push", "(", "input", ")", ";", "}", "}", "flatten", "(", "chunk", ")", ";", "this", ".", "children", "=", "result", ";", "}" ]
Fallback for the non SourceMap environment
[ "Fallback", "for", "the", "non", "SourceMap", "environment" ]
98ce4b3b9bd0fb4893562d7ba1e121952169cb53
https://github.com/sciolist/pellets/blob/98ce4b3b9bd0fb4893562d7ba1e121952169cb53/browser/pellets.js#L4536-L4554
train
christophercrouzet/pillr
lib/utils.js
trimExtension
function trimExtension(filePath) { const ext = path.extname(filePath); return filePath.slice(0, filePath.length - ext.length); }
javascript
function trimExtension(filePath) { const ext = path.extname(filePath); return filePath.slice(0, filePath.length - ext.length); }
[ "function", "trimExtension", "(", "filePath", ")", "{", "const", "ext", "=", "path", ".", "extname", "(", "filePath", ")", ";", "return", "filePath", ".", "slice", "(", "0", ",", "filePath", ".", "length", "-", "ext", ".", "length", ")", ";", "}" ]
Remove the extension.
[ "Remove", "the", "extension", "." ]
411ccd344a03478776c4e8d2e2f9bdc45dc8ee45
https://github.com/christophercrouzet/pillr/blob/411ccd344a03478776c4e8d2e2f9bdc45dc8ee45/lib/utils.js#L21-L24
train
christophercrouzet/pillr
lib/utils.js
asDataMap
function asDataMap(files, mapping, callback) { try { const out = files.reduce((obj, file) => { let key; switch (mapping) { case Mapping.DIR: key = path.dirname(file.path); break; case Mapping.MODULE: key = trimExtension(file.path).replace(PATH_SEP_RE, '.'); break; default: key = file.path; break; } return Object.assign(obj, { [key]: file.data }); }, {}); async.nextTick(callback, null, out); } catch (error) { async.nextTick(callback, error); } }
javascript
function asDataMap(files, mapping, callback) { try { const out = files.reduce((obj, file) => { let key; switch (mapping) { case Mapping.DIR: key = path.dirname(file.path); break; case Mapping.MODULE: key = trimExtension(file.path).replace(PATH_SEP_RE, '.'); break; default: key = file.path; break; } return Object.assign(obj, { [key]: file.data }); }, {}); async.nextTick(callback, null, out); } catch (error) { async.nextTick(callback, error); } }
[ "function", "asDataMap", "(", "files", ",", "mapping", ",", "callback", ")", "{", "try", "{", "const", "out", "=", "files", ".", "reduce", "(", "(", "obj", ",", "file", ")", "=>", "{", "let", "key", ";", "switch", "(", "mapping", ")", "{", "case", "Mapping", ".", "DIR", ":", "key", "=", "path", ".", "dirname", "(", "file", ".", "path", ")", ";", "break", ";", "case", "Mapping", ".", "MODULE", ":", "key", "=", "trimExtension", "(", "file", ".", "path", ")", ".", "replace", "(", "PATH_SEP_RE", ",", "'.'", ")", ";", "break", ";", "default", ":", "key", "=", "file", ".", "path", ";", "break", ";", "}", "return", "Object", ".", "assign", "(", "obj", ",", "{", "[", "key", "]", ":", "file", ".", "data", "}", ")", ";", "}", ",", "{", "}", ")", ";", "async", ".", "nextTick", "(", "callback", ",", "null", ",", "out", ")", ";", "}", "catch", "(", "error", ")", "{", "async", ".", "nextTick", "(", "callback", ",", "error", ")", ";", "}", "}" ]
Map files data with their path as key.
[ "Map", "files", "data", "with", "their", "path", "as", "key", "." ]
411ccd344a03478776c4e8d2e2f9bdc45dc8ee45
https://github.com/christophercrouzet/pillr/blob/411ccd344a03478776c4e8d2e2f9bdc45dc8ee45/lib/utils.js#L28-L50
train
christophercrouzet/pillr
lib/utils.js
mkdir
function mkdir(dirPath, callback) { // Credits: https://github.com/substack/node-mkdirp // Recursively go through the parents. const recurse = () => { mkdir(path.dirname(dirPath), (error) => { if (error) { async.nextTick(callback, error); return; } // Try again. mkdir(dirPath, callback); }); }; // Plan B for when things seem to go wrong. const fallBack = () => { fs.stat(dirPath, (error, stat) => { if (error || !stat.isDirectory()) { async.nextTick( callback, new Error(`${dirPath}: Could not create the directory`) ); return; } async.nextTick(callback, null); }); }; fs.mkdir(dirPath, (error) => { if (!error) { async.nextTick(callback, null); return; } switch (error.code) { case 'ENOENT': recurse(); break; default: fallBack(); break; } }); }
javascript
function mkdir(dirPath, callback) { // Credits: https://github.com/substack/node-mkdirp // Recursively go through the parents. const recurse = () => { mkdir(path.dirname(dirPath), (error) => { if (error) { async.nextTick(callback, error); return; } // Try again. mkdir(dirPath, callback); }); }; // Plan B for when things seem to go wrong. const fallBack = () => { fs.stat(dirPath, (error, stat) => { if (error || !stat.isDirectory()) { async.nextTick( callback, new Error(`${dirPath}: Could not create the directory`) ); return; } async.nextTick(callback, null); }); }; fs.mkdir(dirPath, (error) => { if (!error) { async.nextTick(callback, null); return; } switch (error.code) { case 'ENOENT': recurse(); break; default: fallBack(); break; } }); }
[ "function", "mkdir", "(", "dirPath", ",", "callback", ")", "{", "const", "recurse", "=", "(", ")", "=>", "{", "mkdir", "(", "path", ".", "dirname", "(", "dirPath", ")", ",", "(", "error", ")", "=>", "{", "if", "(", "error", ")", "{", "async", ".", "nextTick", "(", "callback", ",", "error", ")", ";", "return", ";", "}", "mkdir", "(", "dirPath", ",", "callback", ")", ";", "}", ")", ";", "}", ";", "const", "fallBack", "=", "(", ")", "=>", "{", "fs", ".", "stat", "(", "dirPath", ",", "(", "error", ",", "stat", ")", "=>", "{", "if", "(", "error", "||", "!", "stat", ".", "isDirectory", "(", ")", ")", "{", "async", ".", "nextTick", "(", "callback", ",", "new", "Error", "(", "`", "${", "dirPath", "}", "`", ")", ")", ";", "return", ";", "}", "async", ".", "nextTick", "(", "callback", ",", "null", ")", ";", "}", ")", ";", "}", ";", "fs", ".", "mkdir", "(", "dirPath", ",", "(", "error", ")", "=>", "{", "if", "(", "!", "error", ")", "{", "async", ".", "nextTick", "(", "callback", ",", "null", ")", ";", "return", ";", "}", "switch", "(", "error", ".", "code", ")", "{", "case", "'ENOENT'", ":", "recurse", "(", ")", ";", "break", ";", "default", ":", "fallBack", "(", ")", ";", "break", ";", "}", "}", ")", ";", "}" ]
Create a directory and any missing parent directory.
[ "Create", "a", "directory", "and", "any", "missing", "parent", "directory", "." ]
411ccd344a03478776c4e8d2e2f9bdc45dc8ee45
https://github.com/christophercrouzet/pillr/blob/411ccd344a03478776c4e8d2e2f9bdc45dc8ee45/lib/utils.js#L64-L110
train
christophercrouzet/pillr
lib/utils.js
write
function write(filePath, data, mode, callback) { async.series([ cb => mkdir(path.dirname(filePath), cb), (cb) => { if (mode === WriteMode.UTF8) { fs.writeFile(filePath, data, 'utf8', (error) => { if (error) { console.error(`${filePath}: Could not write the file`); } async.nextTick(cb, error); }); } else if (mode === WriteMode.STREAM) { try { data.pipe(fs.createWriteStream(filePath)); async.nextTick(cb, null); } catch (error) { console.error(`${filePath}: Could not create the write stream`); async.nextTick(cb, error); } } }, ], error => async.nextTick(callback, error)); }
javascript
function write(filePath, data, mode, callback) { async.series([ cb => mkdir(path.dirname(filePath), cb), (cb) => { if (mode === WriteMode.UTF8) { fs.writeFile(filePath, data, 'utf8', (error) => { if (error) { console.error(`${filePath}: Could not write the file`); } async.nextTick(cb, error); }); } else if (mode === WriteMode.STREAM) { try { data.pipe(fs.createWriteStream(filePath)); async.nextTick(cb, null); } catch (error) { console.error(`${filePath}: Could not create the write stream`); async.nextTick(cb, error); } } }, ], error => async.nextTick(callback, error)); }
[ "function", "write", "(", "filePath", ",", "data", ",", "mode", ",", "callback", ")", "{", "async", ".", "series", "(", "[", "cb", "=>", "mkdir", "(", "path", ".", "dirname", "(", "filePath", ")", ",", "cb", ")", ",", "(", "cb", ")", "=>", "{", "if", "(", "mode", "===", "WriteMode", ".", "UTF8", ")", "{", "fs", ".", "writeFile", "(", "filePath", ",", "data", ",", "'utf8'", ",", "(", "error", ")", "=>", "{", "if", "(", "error", ")", "{", "console", ".", "error", "(", "`", "${", "filePath", "}", "`", ")", ";", "}", "async", ".", "nextTick", "(", "cb", ",", "error", ")", ";", "}", ")", ";", "}", "else", "if", "(", "mode", "===", "WriteMode", ".", "STREAM", ")", "{", "try", "{", "data", ".", "pipe", "(", "fs", ".", "createWriteStream", "(", "filePath", ")", ")", ";", "async", ".", "nextTick", "(", "cb", ",", "null", ")", ";", "}", "catch", "(", "error", ")", "{", "console", ".", "error", "(", "`", "${", "filePath", "}", "`", ")", ";", "async", ".", "nextTick", "(", "cb", ",", "error", ")", ";", "}", "}", "}", ",", "]", ",", "error", "=>", "async", ".", "nextTick", "(", "callback", ",", "error", ")", ")", ";", "}" ]
Write a file.
[ "Write", "a", "file", "." ]
411ccd344a03478776c4e8d2e2f9bdc45dc8ee45
https://github.com/christophercrouzet/pillr/blob/411ccd344a03478776c4e8d2e2f9bdc45dc8ee45/lib/utils.js#L173-L196
train
pinyin/outline
vendor/transformation-matrix/shear.js
shear
function shear(shx, shy) { return { a: 1, c: shx, e: 0, b: shy, d: 1, f: 0 }; }
javascript
function shear(shx, shy) { return { a: 1, c: shx, e: 0, b: shy, d: 1, f: 0 }; }
[ "function", "shear", "(", "shx", ",", "shy", ")", "{", "return", "{", "a", ":", "1", ",", "c", ":", "shx", ",", "e", ":", "0", ",", "b", ":", "shy", ",", "d", ":", "1", ",", "f", ":", "0", "}", ";", "}" ]
Calculate a shear matrix @param shx Shear on axis x @param shy Shear on axis y @returns {{a: number, b: number, c: number, e: number, d: number, f: number}} Affine matrix
[ "Calculate", "a", "shear", "matrix" ]
e49f05d2f8ab384f5b1d71b2b10875cd48d41051
https://github.com/pinyin/outline/blob/e49f05d2f8ab384f5b1d71b2b10875cd48d41051/vendor/transformation-matrix/shear.js#L14-L19
train
olizilla/instagrab
index.js
apiUrlFor
function apiUrlFor (shortcode, size) { if (!shortcode) throw new Error('shortcode parameter is required') size = size || 'l' var api = 'http://instagram.com/p/%s/media/?size=%s' return util.format(api, shortcode, size) }
javascript
function apiUrlFor (shortcode, size) { if (!shortcode) throw new Error('shortcode parameter is required') size = size || 'l' var api = 'http://instagram.com/p/%s/media/?size=%s' return util.format(api, shortcode, size) }
[ "function", "apiUrlFor", "(", "shortcode", ",", "size", ")", "{", "if", "(", "!", "shortcode", ")", "throw", "new", "Error", "(", "'shortcode parameter is required'", ")", "size", "=", "size", "||", "'l'", "var", "api", "=", "'http://instagram.com/p/%s/media/?size=%s'", "return", "util", ".", "format", "(", "api", ",", "shortcode", ",", "size", ")", "}" ]
Build the api url from it's ingredients
[ "Build", "the", "api", "url", "from", "it", "s", "ingredients" ]
fe21a57a0aeecacaaa37eccc9d06822889d78ba6
https://github.com/olizilla/instagrab/blob/fe21a57a0aeecacaaa37eccc9d06822889d78ba6/index.js#L36-L42
train
olizilla/instagrab
index.js
filenameFor
function filenameFor(shortcode, size) { if (!shortcode) throw new Error('shortcode parameter is required') size = size || 'l' return [shortcode, size, 'jpg'].join('.') }
javascript
function filenameFor(shortcode, size) { if (!shortcode) throw new Error('shortcode parameter is required') size = size || 'l' return [shortcode, size, 'jpg'].join('.') }
[ "function", "filenameFor", "(", "shortcode", ",", "size", ")", "{", "if", "(", "!", "shortcode", ")", "throw", "new", "Error", "(", "'shortcode parameter is required'", ")", "size", "=", "size", "||", "'l'", "return", "[", "shortcode", ",", "size", ",", "'jpg'", "]", ".", "join", "(", "'.'", ")", "}" ]
Make up a useful filename
[ "Make", "up", "a", "useful", "filename" ]
fe21a57a0aeecacaaa37eccc9d06822889d78ba6
https://github.com/olizilla/instagrab/blob/fe21a57a0aeecacaaa37eccc9d06822889d78ba6/index.js#L45-L50
train
olizilla/instagrab
index.js
resolvedUrlFor
function resolvedUrlFor (shortcode, size, cb) { if (typeof size === 'function') { cb = size size = 'l' } cb = cb || function () {} var apiUrl = apiUrlFor(shortcode, size) var opts = url.parse(apiUrl) // http requests use the global Agent (connection pool) and defaults to `Connection: keep-alive` // This causes the test suite to hang, so we explicitly set it to close. // Alternatively, set `opts.agent: false` to opt out of connection pool and default to `Connection: close` // see: http://nodejs.org/api/http.html#http_http_request_options_callback opts.headers = { Connection:'close' } http.get(opts, function (res) { var url = res && res.headers && res.headers.location if (!url) return cb(new Error('Couldn\'t get url; no `location` header on response'), res) cb(null, url) }).on('error', cb) }
javascript
function resolvedUrlFor (shortcode, size, cb) { if (typeof size === 'function') { cb = size size = 'l' } cb = cb || function () {} var apiUrl = apiUrlFor(shortcode, size) var opts = url.parse(apiUrl) // http requests use the global Agent (connection pool) and defaults to `Connection: keep-alive` // This causes the test suite to hang, so we explicitly set it to close. // Alternatively, set `opts.agent: false` to opt out of connection pool and default to `Connection: close` // see: http://nodejs.org/api/http.html#http_http_request_options_callback opts.headers = { Connection:'close' } http.get(opts, function (res) { var url = res && res.headers && res.headers.location if (!url) return cb(new Error('Couldn\'t get url; no `location` header on response'), res) cb(null, url) }).on('error', cb) }
[ "function", "resolvedUrlFor", "(", "shortcode", ",", "size", ",", "cb", ")", "{", "if", "(", "typeof", "size", "===", "'function'", ")", "{", "cb", "=", "size", "size", "=", "'l'", "}", "cb", "=", "cb", "||", "function", "(", ")", "{", "}", "var", "apiUrl", "=", "apiUrlFor", "(", "shortcode", ",", "size", ")", "var", "opts", "=", "url", ".", "parse", "(", "apiUrl", ")", "opts", ".", "headers", "=", "{", "Connection", ":", "'close'", "}", "http", ".", "get", "(", "opts", ",", "function", "(", "res", ")", "{", "var", "url", "=", "res", "&&", "res", ".", "headers", "&&", "res", ".", "headers", ".", "location", "if", "(", "!", "url", ")", "return", "cb", "(", "new", "Error", "(", "'Couldn\\'t get url; no `location` header on response'", ")", ",", "\\'", ")", "res", "}", ")", ".", "cb", "(", "null", ",", "url", ")", "on", "}" ]
Grab the location header from the initial response.
[ "Grab", "the", "location", "header", "from", "the", "initial", "response", "." ]
fe21a57a0aeecacaaa37eccc9d06822889d78ba6
https://github.com/olizilla/instagrab/blob/fe21a57a0aeecacaaa37eccc9d06822889d78ba6/index.js#L59-L83
train
thadeudepaula/enqjs
enq.js
binder
function binder(taskID) { expected++; return function(ret) { expected--; if(!returned && taskID !== 'false') { if (typeof taskID == 'number') returned=[]; else if (typeof taskID == 'string') returned={}; }; taskID !== false ? returned[taskID]=ret : returned = ret; // Timeout needed to increment expected, if next item exists. // If it run without timeout, expected always be 0 and only // the first function of the group will be executed. setTimeout(function(){if (! expected) runQueue();},1); } }
javascript
function binder(taskID) { expected++; return function(ret) { expected--; if(!returned && taskID !== 'false') { if (typeof taskID == 'number') returned=[]; else if (typeof taskID == 'string') returned={}; }; taskID !== false ? returned[taskID]=ret : returned = ret; // Timeout needed to increment expected, if next item exists. // If it run without timeout, expected always be 0 and only // the first function of the group will be executed. setTimeout(function(){if (! expected) runQueue();},1); } }
[ "function", "binder", "(", "taskID", ")", "{", "expected", "++", ";", "return", "function", "(", "ret", ")", "{", "expected", "--", ";", "if", "(", "!", "returned", "&&", "taskID", "!==", "'false'", ")", "{", "if", "(", "typeof", "taskID", "==", "'number'", ")", "returned", "=", "[", "]", ";", "else", "if", "(", "typeof", "taskID", "==", "'string'", ")", "returned", "=", "{", "}", ";", "}", ";", "taskID", "!==", "false", "?", "returned", "[", "taskID", "]", "=", "ret", ":", "returned", "=", "ret", ";", "setTimeout", "(", "function", "(", ")", "{", "if", "(", "!", "expected", ")", "runQueue", "(", ")", ";", "}", ",", "1", ")", ";", "}", "}" ]
Generate the return function for taskObject. Each task needs a specific function to bind the response to correct order of call
[ "Generate", "the", "return", "function", "for", "taskObject", ".", "Each", "task", "needs", "a", "specific", "function", "to", "bind", "the", "response", "to", "correct", "order", "of", "call" ]
e6cf9704a1d1ba5f8c1b8639672ce554cc3b4e1e
https://github.com/thadeudepaula/enqjs/blob/e6cf9704a1d1ba5f8c1b8639672ce554cc3b4e1e/enq.js#L10-L24
train
thadeudepaula/enqjs
enq.js
argumentFilter
function argumentFilter(args){ var ret; if (typeof args[0] == 'object') { args=args[0]; ret={}; for (var i in args) if (args.hasOwnProperty(i) && typeof args[i] == 'function') { ret[i]=args[i]; } return ret; } ret=[]; for (var i=0,ii=args.length;i<ii;i++) if (typeof args[i] == 'function') { ret.push(args[i]); } return ret; }
javascript
function argumentFilter(args){ var ret; if (typeof args[0] == 'object') { args=args[0]; ret={}; for (var i in args) if (args.hasOwnProperty(i) && typeof args[i] == 'function') { ret[i]=args[i]; } return ret; } ret=[]; for (var i=0,ii=args.length;i<ii;i++) if (typeof args[i] == 'function') { ret.push(args[i]); } return ret; }
[ "function", "argumentFilter", "(", "args", ")", "{", "var", "ret", ";", "if", "(", "typeof", "args", "[", "0", "]", "==", "'object'", ")", "{", "args", "=", "args", "[", "0", "]", ";", "ret", "=", "{", "}", ";", "for", "(", "var", "i", "in", "args", ")", "if", "(", "args", ".", "hasOwnProperty", "(", "i", ")", "&&", "typeof", "args", "[", "i", "]", "==", "'function'", ")", "{", "ret", "[", "i", "]", "=", "args", "[", "i", "]", ";", "}", "return", "ret", ";", "}", "ret", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "ii", "=", "args", ".", "length", ";", "i", "<", "ii", ";", "i", "++", ")", "if", "(", "typeof", "args", "[", "i", "]", "==", "'function'", ")", "{", "ret", ".", "push", "(", "args", "[", "i", "]", ")", ";", "}", "return", "ret", ";", "}" ]
If first item of args is an object, it returns the functions contained there else return a list of functions in args
[ "If", "first", "item", "of", "args", "is", "an", "object", "it", "returns", "the", "functions", "contained", "there", "else", "return", "a", "list", "of", "functions", "in", "args" ]
e6cf9704a1d1ba5f8c1b8639672ce554cc3b4e1e
https://github.com/thadeudepaula/enqjs/blob/e6cf9704a1d1ba5f8c1b8639672ce554cc3b4e1e/enq.js#L35-L50
train
thadeudepaula/enqjs
enq.js
runQueue
function runQueue() { var lastReturned = returned instanceof Array ? returned : [returned] , tasks = queued.shift(); if (tasks) tasks = tasks.tasks; returned = undefined; if (tasks instanceof Array) { for (var t=0,tt=tasks.length; t<tt; t++) { tasks[t].apply(taskObject(t),lastReturned); }; return; } if (typeof tasks == 'object') { for (var t in tasks) if (tasks.hasOwnProperty(t)) { tasks[t].apply(taskObject(t),lastReturned); } return; } }
javascript
function runQueue() { var lastReturned = returned instanceof Array ? returned : [returned] , tasks = queued.shift(); if (tasks) tasks = tasks.tasks; returned = undefined; if (tasks instanceof Array) { for (var t=0,tt=tasks.length; t<tt; t++) { tasks[t].apply(taskObject(t),lastReturned); }; return; } if (typeof tasks == 'object') { for (var t in tasks) if (tasks.hasOwnProperty(t)) { tasks[t].apply(taskObject(t),lastReturned); } return; } }
[ "function", "runQueue", "(", ")", "{", "var", "lastReturned", "=", "returned", "instanceof", "Array", "?", "returned", ":", "[", "returned", "]", ",", "tasks", "=", "queued", ".", "shift", "(", ")", ";", "if", "(", "tasks", ")", "tasks", "=", "tasks", ".", "tasks", ";", "returned", "=", "undefined", ";", "if", "(", "tasks", "instanceof", "Array", ")", "{", "for", "(", "var", "t", "=", "0", ",", "tt", "=", "tasks", ".", "length", ";", "t", "<", "tt", ";", "t", "++", ")", "{", "tasks", "[", "t", "]", ".", "apply", "(", "taskObject", "(", "t", ")", ",", "lastReturned", ")", ";", "}", ";", "return", ";", "}", "if", "(", "typeof", "tasks", "==", "'object'", ")", "{", "for", "(", "var", "t", "in", "tasks", ")", "if", "(", "tasks", ".", "hasOwnProperty", "(", "t", ")", ")", "{", "tasks", "[", "t", "]", ".", "apply", "(", "taskObject", "(", "t", ")", ",", "lastReturned", ")", ";", "}", "return", ";", "}", "}" ]
Take the next group of tasks from the stack;
[ "Take", "the", "next", "group", "of", "tasks", "from", "the", "stack", ";" ]
e6cf9704a1d1ba5f8c1b8639672ce554cc3b4e1e
https://github.com/thadeudepaula/enqjs/blob/e6cf9704a1d1ba5f8c1b8639672ce554cc3b4e1e/enq.js#L53-L72
train
thadeudepaula/enqjs
enq.js
enqueue
function enqueue(){ var tasks = argumentFilter(arguments); queued.push({ tasks:tasks }); // Timeout needed to increment expected, if next item exists. // If it run without timeout, expected always be 0 and the functions // will be executed immediately obtaining undefined as parameter. setTimeout(function(){if (! expected) runQueue();},1); return enqueue; }
javascript
function enqueue(){ var tasks = argumentFilter(arguments); queued.push({ tasks:tasks }); // Timeout needed to increment expected, if next item exists. // If it run without timeout, expected always be 0 and the functions // will be executed immediately obtaining undefined as parameter. setTimeout(function(){if (! expected) runQueue();},1); return enqueue; }
[ "function", "enqueue", "(", ")", "{", "var", "tasks", "=", "argumentFilter", "(", "arguments", ")", ";", "queued", ".", "push", "(", "{", "tasks", ":", "tasks", "}", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "if", "(", "!", "expected", ")", "runQueue", "(", ")", ";", "}", ",", "1", ")", ";", "return", "enqueue", ";", "}" ]
Add a new group of tasks in stack.
[ "Add", "a", "new", "group", "of", "tasks", "in", "stack", "." ]
e6cf9704a1d1ba5f8c1b8639672ce554cc3b4e1e
https://github.com/thadeudepaula/enqjs/blob/e6cf9704a1d1ba5f8c1b8639672ce554cc3b4e1e/enq.js#L75-L83
train
MiguelCastillo/p-stream
index.js
readableStream
function readableStream(stream) { return new Promise(function(resolve, reject) { var chunks = { data: [] }; function onData(chunk) { if (!chunks.type) { chunks.type = chunkTypes[typeof chunk]; } chunks.data.push(chunk); } function onEnd() { if (chunks.type === chunkTypes.object) { resolve(Buffer.concat(chunks.data)); } else { resolve(chunks.data.join("")); } } function onError(error) { reject(error); } stream .on("error", onError) .on("data", onData) .on("end", onEnd); }); }
javascript
function readableStream(stream) { return new Promise(function(resolve, reject) { var chunks = { data: [] }; function onData(chunk) { if (!chunks.type) { chunks.type = chunkTypes[typeof chunk]; } chunks.data.push(chunk); } function onEnd() { if (chunks.type === chunkTypes.object) { resolve(Buffer.concat(chunks.data)); } else { resolve(chunks.data.join("")); } } function onError(error) { reject(error); } stream .on("error", onError) .on("data", onData) .on("end", onEnd); }); }
[ "function", "readableStream", "(", "stream", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "var", "chunks", "=", "{", "data", ":", "[", "]", "}", ";", "function", "onData", "(", "chunk", ")", "{", "if", "(", "!", "chunks", ".", "type", ")", "{", "chunks", ".", "type", "=", "chunkTypes", "[", "typeof", "chunk", "]", ";", "}", "chunks", ".", "data", ".", "push", "(", "chunk", ")", ";", "}", "function", "onEnd", "(", ")", "{", "if", "(", "chunks", ".", "type", "===", "chunkTypes", ".", "object", ")", "{", "resolve", "(", "Buffer", ".", "concat", "(", "chunks", ".", "data", ")", ")", ";", "}", "else", "{", "resolve", "(", "chunks", ".", "data", ".", "join", "(", "\"\"", ")", ")", ";", "}", "}", "function", "onError", "(", "error", ")", "{", "reject", "(", "error", ")", ";", "}", "stream", ".", "on", "(", "\"error\"", ",", "onError", ")", ".", "on", "(", "\"data\"", ",", "onData", ")", ".", "on", "(", "\"end\"", ",", "onEnd", ")", ";", "}", ")", ";", "}" ]
Takes in a readable stream and returns a promise. The promise is resolved when all the data is read. Or reject if the stream has errors. @param {Stream} stream - Stream to read from to resolve the promise with. @returns {Promise}
[ "Takes", "in", "a", "readable", "stream", "and", "returns", "a", "promise", ".", "The", "promise", "is", "resolved", "when", "all", "the", "data", "is", "read", ".", "Or", "reject", "if", "the", "stream", "has", "errors", "." ]
e6d1bb92c14cc609d756e862577e984148d7b955
https://github.com/MiguelCastillo/p-stream/blob/e6d1bb92c14cc609d756e862577e984148d7b955/index.js#L15-L47
train
stephenharris/grunt-checkwpversion
tasks/checkwpversion.js
function( version ){ //lowercase version = version.toLowerCase(); //Remove spaces; version = version.replace( ' ', '' ); //Make delimiters all the same version = version.replace( '-', '.' ); version = version.replace( '_', '.' ); version = version.replace( '+', '.' ); var length = version.length; var newVersion = false; newVersion = version[0]; for( var i=1; i < length; i++ ){ var a = version[i-1]; var b = version[i]; if( '.' === a || '.' === b ){ newVersion += b; continue; } var sameType = ( isNaN( a ) === isNaN( b ) ); if( sameType ){ newVersion += b; }else{ newVersion += "."+b; } } //Split at delimiter var versionArray = newVersion.split( '.' ); //Filter empty parts versionArray = versionArray.filter( function(e){ return ( e !== "" ); } ); //Convert special text into character form. versionArray = versionArray.map( function( e ){ switch( e ){ case 'alpha': return 'a'; case 'beta': return 'b'; case 'pl': return 'p'; default: return e; } } ); return versionArray.join('.'); }
javascript
function( version ){ //lowercase version = version.toLowerCase(); //Remove spaces; version = version.replace( ' ', '' ); //Make delimiters all the same version = version.replace( '-', '.' ); version = version.replace( '_', '.' ); version = version.replace( '+', '.' ); var length = version.length; var newVersion = false; newVersion = version[0]; for( var i=1; i < length; i++ ){ var a = version[i-1]; var b = version[i]; if( '.' === a || '.' === b ){ newVersion += b; continue; } var sameType = ( isNaN( a ) === isNaN( b ) ); if( sameType ){ newVersion += b; }else{ newVersion += "."+b; } } //Split at delimiter var versionArray = newVersion.split( '.' ); //Filter empty parts versionArray = versionArray.filter( function(e){ return ( e !== "" ); } ); //Convert special text into character form. versionArray = versionArray.map( function( e ){ switch( e ){ case 'alpha': return 'a'; case 'beta': return 'b'; case 'pl': return 'p'; default: return e; } } ); return versionArray.join('.'); }
[ "function", "(", "version", ")", "{", "version", "=", "version", ".", "toLowerCase", "(", ")", ";", "version", "=", "version", ".", "replace", "(", "' '", ",", "''", ")", ";", "version", "=", "version", ".", "replace", "(", "'-'", ",", "'.'", ")", ";", "version", "=", "version", ".", "replace", "(", "'_'", ",", "'.'", ")", ";", "version", "=", "version", ".", "replace", "(", "'+'", ",", "'.'", ")", ";", "var", "length", "=", "version", ".", "length", ";", "var", "newVersion", "=", "false", ";", "newVersion", "=", "version", "[", "0", "]", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<", "length", ";", "i", "++", ")", "{", "var", "a", "=", "version", "[", "i", "-", "1", "]", ";", "var", "b", "=", "version", "[", "i", "]", ";", "if", "(", "'.'", "===", "a", "||", "'.'", "===", "b", ")", "{", "newVersion", "+=", "b", ";", "continue", ";", "}", "var", "sameType", "=", "(", "isNaN", "(", "a", ")", "===", "isNaN", "(", "b", ")", ")", ";", "if", "(", "sameType", ")", "{", "newVersion", "+=", "b", ";", "}", "else", "{", "newVersion", "+=", "\".\"", "+", "b", ";", "}", "}", "var", "versionArray", "=", "newVersion", ".", "split", "(", "'.'", ")", ";", "versionArray", "=", "versionArray", ".", "filter", "(", "function", "(", "e", ")", "{", "return", "(", "e", "!==", "\"\"", ")", ";", "}", ")", ";", "versionArray", "=", "versionArray", ".", "map", "(", "function", "(", "e", ")", "{", "switch", "(", "e", ")", "{", "case", "'alpha'", ":", "return", "'a'", ";", "case", "'beta'", ":", "return", "'b'", ";", "case", "'pl'", ":", "return", "'p'", ";", "default", ":", "return", "e", ";", "}", "}", ")", ";", "return", "versionArray", ".", "join", "(", "'.'", ")", ";", "}" ]
Sanitize a version string It does the following: * Casts the string to lower case * Empty spaces are removed * Converts accepted delimiters ('.', '_', '-', '+') to '.' * Adds a . between strings and non-strings: e.g. "1.4b1" becomes "1.4.b.1" * Empty components are removed, e.g. "1.4..1" because "1.4.1" * "alpha", "beta", "pl" are converted to their 1-character equivalents: "a", "b", "p" @param version @returns
[ "Sanitize", "a", "version", "string" ]
42172ead82c87693726d2116830b5a286b115a2a
https://github.com/stephenharris/grunt-checkwpversion/blob/42172ead82c87693726d2116830b5a286b115a2a/tasks/checkwpversion.js#L144-L206
train
stephenharris/grunt-checkwpversion
tasks/checkwpversion.js
function ( version, options ){ var matches; //First if version is 'readme' or 'plugin' version values if( version === 'readme' ){ var readme = grunt.file.read( options.readme ); matches = readme.match( new RegExp("^Stable tag:\\s*(\\S+)","im") ); if( matches.length <= 1 ){ grunt.fail.fatal( 'Could not find version in "' + options.readme + '"' ); } version = matches[1]; }else if( version === 'plugin' ){ var plugin = grunt.file.read( options.plugin ); matches = plugin.match( new RegExp("^[\* ]*Version:\\s*(\\S+)","im") ); if( matches.length <= 1 ){ grunt.fail.fatal( 'Could not find version in "' + options.readme + '"' ); } version = matches[1]; } return version; }
javascript
function ( version, options ){ var matches; //First if version is 'readme' or 'plugin' version values if( version === 'readme' ){ var readme = grunt.file.read( options.readme ); matches = readme.match( new RegExp("^Stable tag:\\s*(\\S+)","im") ); if( matches.length <= 1 ){ grunt.fail.fatal( 'Could not find version in "' + options.readme + '"' ); } version = matches[1]; }else if( version === 'plugin' ){ var plugin = grunt.file.read( options.plugin ); matches = plugin.match( new RegExp("^[\* ]*Version:\\s*(\\S+)","im") ); if( matches.length <= 1 ){ grunt.fail.fatal( 'Could not find version in "' + options.readme + '"' ); } version = matches[1]; } return version; }
[ "function", "(", "version", ",", "options", ")", "{", "var", "matches", ";", "if", "(", "version", "===", "'readme'", ")", "{", "var", "readme", "=", "grunt", ".", "file", ".", "read", "(", "options", ".", "readme", ")", ";", "matches", "=", "readme", ".", "match", "(", "new", "RegExp", "(", "\"^Stable tag:\\\\s*(\\\\S+)\"", ",", "\\\\", ")", ")", ";", "\\\\", "\"im\"", "}", "else", "if", "(", "matches", ".", "length", "<=", "1", ")", "{", "grunt", ".", "fail", ".", "fatal", "(", "'Could not find version in \"'", "+", "options", ".", "readme", "+", "'\"'", ")", ";", "}", "version", "=", "matches", "[", "1", "]", ";", "}" ]
If version is 'readme' or 'plugin', attempts to extract the version stored in the corresponding files as specified by options.
[ "If", "version", "is", "readme", "or", "plugin", "attempts", "to", "extract", "the", "version", "stored", "in", "the", "corresponding", "files", "as", "specified", "by", "options", "." ]
42172ead82c87693726d2116830b5a286b115a2a
https://github.com/stephenharris/grunt-checkwpversion/blob/42172ead82c87693726d2116830b5a286b115a2a/tasks/checkwpversion.js#L239-L263
train
altshift/altshift
lib/altshift/application.js
register
function register(app) { //Check if registered twice if (applicationCurrent === app) { return; } //Only one application can be registered if (applicationCurrent) { throw new core.Error({ code: 'application-registered', message: 'An application was already registered' }); } //Set all handlers Interface.ensure(app, IApplication); applicationCurrent = app; currentHandlers.SIGINT = function () { console.log('Application interrupted'); app.exit(); }; /* FIXME: Eclipse bug currentHandlers.SIGTERM = function () { console.log('Killing in the name of!'); unregister(); process.exit(); };*/ currentHandlers.uncaughtException = function (error) { app.handleError(error); }; currentHandlers.exit = function () { exports.unregister(); }; EVENTS.forEach(function (event) { if (currentHandlers[event]) { process.on(event, currentHandlers[event]); } }); //Start application applicationCurrent.start(); }
javascript
function register(app) { //Check if registered twice if (applicationCurrent === app) { return; } //Only one application can be registered if (applicationCurrent) { throw new core.Error({ code: 'application-registered', message: 'An application was already registered' }); } //Set all handlers Interface.ensure(app, IApplication); applicationCurrent = app; currentHandlers.SIGINT = function () { console.log('Application interrupted'); app.exit(); }; /* FIXME: Eclipse bug currentHandlers.SIGTERM = function () { console.log('Killing in the name of!'); unregister(); process.exit(); };*/ currentHandlers.uncaughtException = function (error) { app.handleError(error); }; currentHandlers.exit = function () { exports.unregister(); }; EVENTS.forEach(function (event) { if (currentHandlers[event]) { process.on(event, currentHandlers[event]); } }); //Start application applicationCurrent.start(); }
[ "function", "register", "(", "app", ")", "{", "if", "(", "applicationCurrent", "===", "app", ")", "{", "return", ";", "}", "if", "(", "applicationCurrent", ")", "{", "throw", "new", "core", ".", "Error", "(", "{", "code", ":", "'application-registered'", ",", "message", ":", "'An application was already registered'", "}", ")", ";", "}", "Interface", ".", "ensure", "(", "app", ",", "IApplication", ")", ";", "applicationCurrent", "=", "app", ";", "currentHandlers", ".", "SIGINT", "=", "function", "(", ")", "{", "console", ".", "log", "(", "'Application interrupted'", ")", ";", "app", ".", "exit", "(", ")", ";", "}", ";", "currentHandlers", ".", "uncaughtException", "=", "function", "(", "error", ")", "{", "app", ".", "handleError", "(", "error", ")", ";", "}", ";", "currentHandlers", ".", "exit", "=", "function", "(", ")", "{", "exports", ".", "unregister", "(", ")", ";", "}", ";", "EVENTS", ".", "forEach", "(", "function", "(", "event", ")", "{", "if", "(", "currentHandlers", "[", "event", "]", ")", "{", "process", ".", "on", "(", "event", ",", "currentHandlers", "[", "event", "]", ")", ";", "}", "}", ")", ";", "applicationCurrent", ".", "start", "(", ")", ";", "}" ]
Register app as the current executing application. This will also register all error handler for uncaught exceptions @param {Application} app @return undefined
[ "Register", "app", "as", "the", "current", "executing", "application", ".", "This", "will", "also", "register", "all", "error", "handler", "for", "uncaught", "exceptions" ]
5c051157e6f558636c8e12081b6707caa66249de
https://github.com/altshift/altshift/blob/5c051157e6f558636c8e12081b6707caa66249de/lib/altshift/application.js#L36-L83
train
altshift/altshift
lib/altshift/application.js
unregister
function unregister() { if (!applicationCurrent) { return; } applicationCurrent.stop(); EVENTS.forEach(function (event) { process.removeListener(event, currentHandlers[event]); }); applicationCurrent = null; currentHandlers = {}; }
javascript
function unregister() { if (!applicationCurrent) { return; } applicationCurrent.stop(); EVENTS.forEach(function (event) { process.removeListener(event, currentHandlers[event]); }); applicationCurrent = null; currentHandlers = {}; }
[ "function", "unregister", "(", ")", "{", "if", "(", "!", "applicationCurrent", ")", "{", "return", ";", "}", "applicationCurrent", ".", "stop", "(", ")", ";", "EVENTS", ".", "forEach", "(", "function", "(", "event", ")", "{", "process", ".", "removeListener", "(", "event", ",", "currentHandlers", "[", "event", "]", ")", ";", "}", ")", ";", "applicationCurrent", "=", "null", ";", "currentHandlers", "=", "{", "}", ";", "}" ]
Unregister current application and remove all corrsponding listeners @return undefined
[ "Unregister", "current", "application", "and", "remove", "all", "corrsponding", "listeners" ]
5c051157e6f558636c8e12081b6707caa66249de
https://github.com/altshift/altshift/blob/5c051157e6f558636c8e12081b6707caa66249de/lib/altshift/application.js#L90-L102
train
altshift/altshift
lib/altshift/application.js
function (config) { config = config || {}; if (config.onStart !== undefined) { if (!isFunction(config.onStart)) { throw new core.TypeError({ code: 'application-configure', message: "config.onStart must be a function" }); } this.onStart = config.onStart; } if (config.onStop !== undefined) { if (!isFunction(config.onStop)) { throw new core.TypeError({ code: 'application-configure', message: "config.onStop must be a function" }); } this.onStop = config.onStop; } return this; }
javascript
function (config) { config = config || {}; if (config.onStart !== undefined) { if (!isFunction(config.onStart)) { throw new core.TypeError({ code: 'application-configure', message: "config.onStart must be a function" }); } this.onStart = config.onStart; } if (config.onStop !== undefined) { if (!isFunction(config.onStop)) { throw new core.TypeError({ code: 'application-configure', message: "config.onStop must be a function" }); } this.onStop = config.onStop; } return this; }
[ "function", "(", "config", ")", "{", "config", "=", "config", "||", "{", "}", ";", "if", "(", "config", ".", "onStart", "!==", "undefined", ")", "{", "if", "(", "!", "isFunction", "(", "config", ".", "onStart", ")", ")", "{", "throw", "new", "core", ".", "TypeError", "(", "{", "code", ":", "'application-configure'", ",", "message", ":", "\"config.onStart must be a function\"", "}", ")", ";", "}", "this", ".", "onStart", "=", "config", ".", "onStart", ";", "}", "if", "(", "config", ".", "onStop", "!==", "undefined", ")", "{", "if", "(", "!", "isFunction", "(", "config", ".", "onStop", ")", ")", "{", "throw", "new", "core", ".", "TypeError", "(", "{", "code", ":", "'application-configure'", ",", "message", ":", "\"config.onStop must be a function\"", "}", ")", ";", "}", "this", ".", "onStop", "=", "config", ".", "onStop", ";", "}", "return", "this", ";", "}" ]
Configure the application @param {Object} config @return this
[ "Configure", "the", "application" ]
5c051157e6f558636c8e12081b6707caa66249de
https://github.com/altshift/altshift/blob/5c051157e6f558636c8e12081b6707caa66249de/lib/altshift/application.js#L162-L187
train
altshift/altshift
lib/altshift/application.js
function (error) { if (!this.started) { return; } var errorHandlers = this.errorHandlers, length = errorHandlers.length, errorHandler, errorHandled = false, errorString, i; //Exit handling if (error instanceof SystemExit) { this._exit(error.code); return; } try { for (i = 0; i < length; i += 1) { errorHandler = errorHandlers[i]; errorHandled = !!errorHandler(error); if (errorHandled) { return; } } } catch (e) { this._printError(e); this._exit(1); } //Default error handling errorString = '' + (error.stack || error); this._printError(errorString); this._exit(1); }
javascript
function (error) { if (!this.started) { return; } var errorHandlers = this.errorHandlers, length = errorHandlers.length, errorHandler, errorHandled = false, errorString, i; //Exit handling if (error instanceof SystemExit) { this._exit(error.code); return; } try { for (i = 0; i < length; i += 1) { errorHandler = errorHandlers[i]; errorHandled = !!errorHandler(error); if (errorHandled) { return; } } } catch (e) { this._printError(e); this._exit(1); } //Default error handling errorString = '' + (error.stack || error); this._printError(errorString); this._exit(1); }
[ "function", "(", "error", ")", "{", "if", "(", "!", "this", ".", "started", ")", "{", "return", ";", "}", "var", "errorHandlers", "=", "this", ".", "errorHandlers", ",", "length", "=", "errorHandlers", ".", "length", ",", "errorHandler", ",", "errorHandled", "=", "false", ",", "errorString", ",", "i", ";", "if", "(", "error", "instanceof", "SystemExit", ")", "{", "this", ".", "_exit", "(", "error", ".", "code", ")", ";", "return", ";", "}", "try", "{", "for", "(", "i", "=", "0", ";", "i", "<", "length", ";", "i", "+=", "1", ")", "{", "errorHandler", "=", "errorHandlers", "[", "i", "]", ";", "errorHandled", "=", "!", "!", "errorHandler", "(", "error", ")", ";", "if", "(", "errorHandled", ")", "{", "return", ";", "}", "}", "}", "catch", "(", "e", ")", "{", "this", ".", "_printError", "(", "e", ")", ";", "this", ".", "_exit", "(", "1", ")", ";", "}", "errorString", "=", "''", "+", "(", "error", ".", "stack", "||", "error", ")", ";", "this", ".", "_printError", "(", "errorString", ")", ";", "this", ".", "_exit", "(", "1", ")", ";", "}" ]
Handle one error @param {*} error
[ "Handle", "one", "error" ]
5c051157e6f558636c8e12081b6707caa66249de
https://github.com/altshift/altshift/blob/5c051157e6f558636c8e12081b6707caa66249de/lib/altshift/application.js#L222-L258
train
RnbWd/parse-browserify
lib/cloud.js
function(name, data, options) { options = options || {}; var request = Parse._request({ route: "functions", className: name, method: 'POST', useMasterKey: options.useMasterKey, data: Parse._encode(data, null, true) }); return request.then(function(resp) { return Parse._decode(null, resp).result; })._thenRunCallbacks(options); }
javascript
function(name, data, options) { options = options || {}; var request = Parse._request({ route: "functions", className: name, method: 'POST', useMasterKey: options.useMasterKey, data: Parse._encode(data, null, true) }); return request.then(function(resp) { return Parse._decode(null, resp).result; })._thenRunCallbacks(options); }
[ "function", "(", "name", ",", "data", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "request", "=", "Parse", ".", "_request", "(", "{", "route", ":", "\"functions\"", ",", "className", ":", "name", ",", "method", ":", "'POST'", ",", "useMasterKey", ":", "options", ".", "useMasterKey", ",", "data", ":", "Parse", ".", "_encode", "(", "data", ",", "null", ",", "true", ")", "}", ")", ";", "return", "request", ".", "then", "(", "function", "(", "resp", ")", "{", "return", "Parse", ".", "_decode", "(", "null", ",", "resp", ")", ".", "result", ";", "}", ")", ".", "_thenRunCallbacks", "(", "options", ")", ";", "}" ]
Makes a call to a cloud function. @param {String} name The function name. @param {Object} data The parameters to send to the cloud function. @param {Object} options A Backbone-style options object options.success, if set, should be a function to handle a successful call to a cloud function. options.error should be a function that handles an error running the cloud function. Both functions are optional. Both functions take a single argument. @return {Parse.Promise} A promise that will be resolved with the result of the function.
[ "Makes", "a", "call", "to", "a", "cloud", "function", "." ]
c19c1b798e4010a552e130b1a9ce3b5d084dc101
https://github.com/RnbWd/parse-browserify/blob/c19c1b798e4010a552e130b1a9ce3b5d084dc101/lib/cloud.js#L28-L42
train
ikondrat/franky
src/etc/views.js
function (/**Array|Object*/tmpl, /**Object*/data) /**String*/{ var res= ""; // there are thre possible declarations array of functions, string and function // array case if (franky.isArray(tmpl)) { res = franky.map(tmpl, function (item) { return typeof item === "string" ? item: item(data); }).join(""); // function case } else if (franky.isFunction(tmpl)) { res = tmpl(data); // default string case } else { res = tmpl.toString(); } return res; }
javascript
function (/**Array|Object*/tmpl, /**Object*/data) /**String*/{ var res= ""; // there are thre possible declarations array of functions, string and function // array case if (franky.isArray(tmpl)) { res = franky.map(tmpl, function (item) { return typeof item === "string" ? item: item(data); }).join(""); // function case } else if (franky.isFunction(tmpl)) { res = tmpl(data); // default string case } else { res = tmpl.toString(); } return res; }
[ "function", "(", "tmpl", ",", "data", ")", "{", "var", "res", "=", "\"\"", ";", "if", "(", "franky", ".", "isArray", "(", "tmpl", ")", ")", "{", "res", "=", "franky", ".", "map", "(", "tmpl", ",", "function", "(", "item", ")", "{", "return", "typeof", "item", "===", "\"string\"", "?", "item", ":", "item", "(", "data", ")", ";", "}", ")", ".", "join", "(", "\"\"", ")", ";", "}", "else", "if", "(", "franky", ".", "isFunction", "(", "tmpl", ")", ")", "{", "res", "=", "tmpl", "(", "data", ")", ";", "}", "else", "{", "res", "=", "tmpl", ".", "toString", "(", ")", ";", "}", "return", "res", ";", "}" ]
Returns processed string
[ "Returns", "processed", "string" ]
6a7368891f39620a225e37c4a56d2bf99644c3e7
https://github.com/ikondrat/franky/blob/6a7368891f39620a225e37c4a56d2bf99644c3e7/src/etc/views.js#L114-L133
train
ikondrat/franky
src/etc/views.js
function (/**String*/name, /**Object*/data) /**String*/ { var self = this; var template = data && data.views ? data.views.templates[name] : this.templates[name]; if(!template){ return ''; } return self.getContent(template, data); }
javascript
function (/**String*/name, /**Object*/data) /**String*/ { var self = this; var template = data && data.views ? data.views.templates[name] : this.templates[name]; if(!template){ return ''; } return self.getContent(template, data); }
[ "function", "(", "name", ",", "data", ")", "{", "var", "self", "=", "this", ";", "var", "template", "=", "data", "&&", "data", ".", "views", "?", "data", ".", "views", ".", "templates", "[", "name", "]", ":", "this", ".", "templates", "[", "name", "]", ";", "if", "(", "!", "template", ")", "{", "return", "''", ";", "}", "return", "self", ".", "getContent", "(", "template", ",", "data", ")", ";", "}" ]
Gets transformed value by defined template and data
[ "Gets", "transformed", "value", "by", "defined", "template", "and", "data" ]
6a7368891f39620a225e37c4a56d2bf99644c3e7
https://github.com/ikondrat/franky/blob/6a7368891f39620a225e37c4a56d2bf99644c3e7/src/etc/views.js#L136-L144
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/selection.js
fixInitialSelection
function fixInitialSelection( root, nativeSel, doFocus ) { // It may happen that setting proper selection will // cause focus to be fired (even without actually focusing root). // Cancel it because focus shouldn't be fired when retriving selection. (#10115) var listener = root.on( 'focus', function( evt ) { evt.cancel(); }, null, null, -100 ); // FF && Webkit. if ( !CKEDITOR.env.ie ) { var range = new CKEDITOR.dom.range( root ); range.moveToElementEditStart( root ); var nativeRange = root.getDocument().$.createRange(); nativeRange.setStart( range.startContainer.$, range.startOffset ); nativeRange.collapse( 1 ); nativeSel.removeAllRanges(); nativeSel.addRange( nativeRange ); } else { // IE in specific case may also fire selectionchange. // We cannot block bubbling selectionchange, so at least we // can prevent from falling into inf recursion caused by fix for #9699 // (see wysiwygarea plugin). // http://dev.ckeditor.com/ticket/10438#comment:13 var listener2 = root.getDocument().on( 'selectionchange', function( evt ) { evt.cancel(); }, null, null, -100 ); } doFocus && root.focus(); listener.removeListener(); listener2 && listener2.removeListener(); }
javascript
function fixInitialSelection( root, nativeSel, doFocus ) { // It may happen that setting proper selection will // cause focus to be fired (even without actually focusing root). // Cancel it because focus shouldn't be fired when retriving selection. (#10115) var listener = root.on( 'focus', function( evt ) { evt.cancel(); }, null, null, -100 ); // FF && Webkit. if ( !CKEDITOR.env.ie ) { var range = new CKEDITOR.dom.range( root ); range.moveToElementEditStart( root ); var nativeRange = root.getDocument().$.createRange(); nativeRange.setStart( range.startContainer.$, range.startOffset ); nativeRange.collapse( 1 ); nativeSel.removeAllRanges(); nativeSel.addRange( nativeRange ); } else { // IE in specific case may also fire selectionchange. // We cannot block bubbling selectionchange, so at least we // can prevent from falling into inf recursion caused by fix for #9699 // (see wysiwygarea plugin). // http://dev.ckeditor.com/ticket/10438#comment:13 var listener2 = root.getDocument().on( 'selectionchange', function( evt ) { evt.cancel(); }, null, null, -100 ); } doFocus && root.focus(); listener.removeListener(); listener2 && listener2.removeListener(); }
[ "function", "fixInitialSelection", "(", "root", ",", "nativeSel", ",", "doFocus", ")", "{", "var", "listener", "=", "root", ".", "on", "(", "'focus'", ",", "function", "(", "evt", ")", "{", "evt", ".", "cancel", "(", ")", ";", "}", ",", "null", ",", "null", ",", "-", "100", ")", ";", "if", "(", "!", "CKEDITOR", ".", "env", ".", "ie", ")", "{", "var", "range", "=", "new", "CKEDITOR", ".", "dom", ".", "range", "(", "root", ")", ";", "range", ".", "moveToElementEditStart", "(", "root", ")", ";", "var", "nativeRange", "=", "root", ".", "getDocument", "(", ")", ".", "$", ".", "createRange", "(", ")", ";", "nativeRange", ".", "setStart", "(", "range", ".", "startContainer", ".", "$", ",", "range", ".", "startOffset", ")", ";", "nativeRange", ".", "collapse", "(", "1", ")", ";", "nativeSel", ".", "removeAllRanges", "(", ")", ";", "nativeSel", ".", "addRange", "(", "nativeRange", ")", ";", "}", "else", "{", "var", "listener2", "=", "root", ".", "getDocument", "(", ")", ".", "on", "(", "'selectionchange'", ",", "function", "(", "evt", ")", "{", "evt", ".", "cancel", "(", ")", ";", "}", ",", "null", ",", "null", ",", "-", "100", ")", ";", "}", "doFocus", "&&", "root", ".", "focus", "(", ")", ";", "listener", ".", "removeListener", "(", ")", ";", "listener2", "&&", "listener2", ".", "removeListener", "(", ")", ";", "}" ]
Read the comments in selection constructor.
[ "Read", "the", "comments", "in", "selection", "constructor", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/selection.js#L208-L243
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/selection.js
hideSelection
function hideSelection( editor ) { var style = CKEDITOR.env.ie ? 'display:none' : 'position:fixed;top:0;left:-1000px', hiddenEl = CKEDITOR.dom.element.createFromHtml( '<div data-cke-hidden-sel="1" data-cke-temp="1" style="' + style + '">&nbsp;</div>', editor.document ); editor.fire( 'lockSnapshot' ); editor.editable().append( hiddenEl ); // Always use real selection to avoid overriding locked one (http://dev.ckeditor.com/ticket/11104#comment:13). var sel = editor.getSelection( 1 ), range = editor.createRange(), // Cancel selectionchange fired by selectRanges - prevent from firing selectionChange. listener = sel.root.on( 'selectionchange', function( evt ) { evt.cancel(); }, null, null, 0 ); range.setStartAt( hiddenEl, CKEDITOR.POSITION_AFTER_START ); range.setEndAt( hiddenEl, CKEDITOR.POSITION_BEFORE_END ); sel.selectRanges( [ range ] ); listener.removeListener(); editor.fire( 'unlockSnapshot' ); // Set this value at the end, so reset() executed by selectRanges() // will clean up old hidden selection container. editor._.hiddenSelectionContainer = hiddenEl; }
javascript
function hideSelection( editor ) { var style = CKEDITOR.env.ie ? 'display:none' : 'position:fixed;top:0;left:-1000px', hiddenEl = CKEDITOR.dom.element.createFromHtml( '<div data-cke-hidden-sel="1" data-cke-temp="1" style="' + style + '">&nbsp;</div>', editor.document ); editor.fire( 'lockSnapshot' ); editor.editable().append( hiddenEl ); // Always use real selection to avoid overriding locked one (http://dev.ckeditor.com/ticket/11104#comment:13). var sel = editor.getSelection( 1 ), range = editor.createRange(), // Cancel selectionchange fired by selectRanges - prevent from firing selectionChange. listener = sel.root.on( 'selectionchange', function( evt ) { evt.cancel(); }, null, null, 0 ); range.setStartAt( hiddenEl, CKEDITOR.POSITION_AFTER_START ); range.setEndAt( hiddenEl, CKEDITOR.POSITION_BEFORE_END ); sel.selectRanges( [ range ] ); listener.removeListener(); editor.fire( 'unlockSnapshot' ); // Set this value at the end, so reset() executed by selectRanges() // will clean up old hidden selection container. editor._.hiddenSelectionContainer = hiddenEl; }
[ "function", "hideSelection", "(", "editor", ")", "{", "var", "style", "=", "CKEDITOR", ".", "env", ".", "ie", "?", "'display:none'", ":", "'position:fixed;top:0;left:-1000px'", ",", "hiddenEl", "=", "CKEDITOR", ".", "dom", ".", "element", ".", "createFromHtml", "(", "'<div data-cke-hidden-sel=\"1\" data-cke-temp=\"1\" style=\"'", "+", "style", "+", "'\">&nbsp;</div>'", ",", "editor", ".", "document", ")", ";", "editor", ".", "fire", "(", "'lockSnapshot'", ")", ";", "editor", ".", "editable", "(", ")", ".", "append", "(", "hiddenEl", ")", ";", "var", "sel", "=", "editor", ".", "getSelection", "(", "1", ")", ",", "range", "=", "editor", ".", "createRange", "(", ")", ",", "listener", "=", "sel", ".", "root", ".", "on", "(", "'selectionchange'", ",", "function", "(", "evt", ")", "{", "evt", ".", "cancel", "(", ")", ";", "}", ",", "null", ",", "null", ",", "0", ")", ";", "range", ".", "setStartAt", "(", "hiddenEl", ",", "CKEDITOR", ".", "POSITION_AFTER_START", ")", ";", "range", ".", "setEndAt", "(", "hiddenEl", ",", "CKEDITOR", ".", "POSITION_BEFORE_END", ")", ";", "sel", ".", "selectRanges", "(", "[", "range", "]", ")", ";", "listener", ".", "removeListener", "(", ")", ";", "editor", ".", "fire", "(", "'unlockSnapshot'", ")", ";", "editor", ".", "_", ".", "hiddenSelectionContainer", "=", "hiddenEl", ";", "}" ]
Creates cke_hidden_sel container and puts real selection there.
[ "Creates", "cke_hidden_sel", "container", "and", "puts", "real", "selection", "there", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/selection.js#L246-L275
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/selection.js
getOnKeyDownListener
function getOnKeyDownListener( editor ) { var keystrokes = { 37: 1, 39: 1, 8: 1, 46: 1 }; return function( evt ) { var keystroke = evt.data.getKeystroke(); // Handle only left/right/del/bspace keys. if ( !keystrokes[ keystroke ] ) return; var sel = editor.getSelection(), ranges = sel.getRanges(), range = ranges[ 0 ]; // Handle only single range and it has to be collapsed. if ( ranges.length != 1 || !range.collapsed ) return; var next = range[ keystroke < 38 ? 'getPreviousEditableNode' : 'getNextEditableNode' ](); if ( next && next.type == CKEDITOR.NODE_ELEMENT && next.getAttribute( 'contenteditable' ) == 'false' ) { editor.getSelection().fake( next ); evt.data.preventDefault(); evt.cancel(); } }; }
javascript
function getOnKeyDownListener( editor ) { var keystrokes = { 37: 1, 39: 1, 8: 1, 46: 1 }; return function( evt ) { var keystroke = evt.data.getKeystroke(); // Handle only left/right/del/bspace keys. if ( !keystrokes[ keystroke ] ) return; var sel = editor.getSelection(), ranges = sel.getRanges(), range = ranges[ 0 ]; // Handle only single range and it has to be collapsed. if ( ranges.length != 1 || !range.collapsed ) return; var next = range[ keystroke < 38 ? 'getPreviousEditableNode' : 'getNextEditableNode' ](); if ( next && next.type == CKEDITOR.NODE_ELEMENT && next.getAttribute( 'contenteditable' ) == 'false' ) { editor.getSelection().fake( next ); evt.data.preventDefault(); evt.cancel(); } }; }
[ "function", "getOnKeyDownListener", "(", "editor", ")", "{", "var", "keystrokes", "=", "{", "37", ":", "1", ",", "39", ":", "1", ",", "8", ":", "1", ",", "46", ":", "1", "}", ";", "return", "function", "(", "evt", ")", "{", "var", "keystroke", "=", "evt", ".", "data", ".", "getKeystroke", "(", ")", ";", "if", "(", "!", "keystrokes", "[", "keystroke", "]", ")", "return", ";", "var", "sel", "=", "editor", ".", "getSelection", "(", ")", ",", "ranges", "=", "sel", ".", "getRanges", "(", ")", ",", "range", "=", "ranges", "[", "0", "]", ";", "if", "(", "ranges", ".", "length", "!=", "1", "||", "!", "range", ".", "collapsed", ")", "return", ";", "var", "next", "=", "range", "[", "keystroke", "<", "38", "?", "'getPreviousEditableNode'", ":", "'getNextEditableNode'", "]", "(", ")", ";", "if", "(", "next", "&&", "next", ".", "type", "==", "CKEDITOR", ".", "NODE_ELEMENT", "&&", "next", ".", "getAttribute", "(", "'contenteditable'", ")", "==", "'false'", ")", "{", "editor", ".", "getSelection", "(", ")", ".", "fake", "(", "next", ")", ";", "evt", ".", "data", ".", "preventDefault", "(", ")", ";", "evt", ".", "cancel", "(", ")", ";", "}", "}", ";", "}" ]
Handle left, right, delete and backspace keystrokes next to non-editable elements by faking selection on them.
[ "Handle", "left", "right", "delete", "and", "backspace", "keystrokes", "next", "to", "non", "-", "editable", "elements", "by", "faking", "selection", "on", "them", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/selection.js#L357-L383
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/selection.js
getNonEditableFakeSelectionReceiver
function getNonEditableFakeSelectionReceiver( ranges ) { var enclosedNode, shrinkedNode, clone, range; if ( ranges.length == 1 && !( range = ranges[ 0 ] ).collapsed && ( enclosedNode = range.getEnclosedNode() ) && enclosedNode.type == CKEDITOR.NODE_ELEMENT ) { // So far we can't say that enclosed element is non-editable. Before checking, // we'll shrink range (clone). Shrinking will stop on non-editable range, or // innermost element (#11114). clone = range.clone(); clone.shrink( CKEDITOR.SHRINK_ELEMENT, true ); // If shrinked range still encloses an element, check this one (shrink stops only on non-editable elements). if ( ( shrinkedNode = clone.getEnclosedNode() ) && shrinkedNode.type == CKEDITOR.NODE_ELEMENT ) enclosedNode = shrinkedNode; if ( enclosedNode.getAttribute( 'contenteditable' ) == 'false' ) return enclosedNode; } }
javascript
function getNonEditableFakeSelectionReceiver( ranges ) { var enclosedNode, shrinkedNode, clone, range; if ( ranges.length == 1 && !( range = ranges[ 0 ] ).collapsed && ( enclosedNode = range.getEnclosedNode() ) && enclosedNode.type == CKEDITOR.NODE_ELEMENT ) { // So far we can't say that enclosed element is non-editable. Before checking, // we'll shrink range (clone). Shrinking will stop on non-editable range, or // innermost element (#11114). clone = range.clone(); clone.shrink( CKEDITOR.SHRINK_ELEMENT, true ); // If shrinked range still encloses an element, check this one (shrink stops only on non-editable elements). if ( ( shrinkedNode = clone.getEnclosedNode() ) && shrinkedNode.type == CKEDITOR.NODE_ELEMENT ) enclosedNode = shrinkedNode; if ( enclosedNode.getAttribute( 'contenteditable' ) == 'false' ) return enclosedNode; } }
[ "function", "getNonEditableFakeSelectionReceiver", "(", "ranges", ")", "{", "var", "enclosedNode", ",", "shrinkedNode", ",", "clone", ",", "range", ";", "if", "(", "ranges", ".", "length", "==", "1", "&&", "!", "(", "range", "=", "ranges", "[", "0", "]", ")", ".", "collapsed", "&&", "(", "enclosedNode", "=", "range", ".", "getEnclosedNode", "(", ")", ")", "&&", "enclosedNode", ".", "type", "==", "CKEDITOR", ".", "NODE_ELEMENT", ")", "{", "clone", "=", "range", ".", "clone", "(", ")", ";", "clone", ".", "shrink", "(", "CKEDITOR", ".", "SHRINK_ELEMENT", ",", "true", ")", ";", "if", "(", "(", "shrinkedNode", "=", "clone", ".", "getEnclosedNode", "(", ")", ")", "&&", "shrinkedNode", ".", "type", "==", "CKEDITOR", ".", "NODE_ELEMENT", ")", "enclosedNode", "=", "shrinkedNode", ";", "if", "(", "enclosedNode", ".", "getAttribute", "(", "'contenteditable'", ")", "==", "'false'", ")", "return", "enclosedNode", ";", "}", "}" ]
If fake selection should be applied this function will return instance of CKEDITOR.dom.element which should gain fake selection.
[ "If", "fake", "selection", "should", "be", "applied", "this", "function", "will", "return", "instance", "of", "CKEDITOR", ".", "dom", ".", "element", "which", "should", "gain", "fake", "selection", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/selection.js#L387-L405
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/selection.js
onHover
function onHover( evt ) { evt = evt.data.$; if ( textRng ) { // Read the current cursor. var rngEnd = body.$.createTextRange(); moveRangeToPoint( rngEnd, evt.clientX, evt.clientY ); // Handle drag directions. textRng.setEndPoint( startRng.compareEndPoints( 'StartToStart', rngEnd ) < 0 ? 'EndToEnd' : 'StartToStart', rngEnd ); // Update selection with new range. textRng.select(); } }
javascript
function onHover( evt ) { evt = evt.data.$; if ( textRng ) { // Read the current cursor. var rngEnd = body.$.createTextRange(); moveRangeToPoint( rngEnd, evt.clientX, evt.clientY ); // Handle drag directions. textRng.setEndPoint( startRng.compareEndPoints( 'StartToStart', rngEnd ) < 0 ? 'EndToEnd' : 'StartToStart', rngEnd ); // Update selection with new range. textRng.select(); } }
[ "function", "onHover", "(", "evt", ")", "{", "evt", "=", "evt", ".", "data", ".", "$", ";", "if", "(", "textRng", ")", "{", "var", "rngEnd", "=", "body", ".", "$", ".", "createTextRange", "(", ")", ";", "moveRangeToPoint", "(", "rngEnd", ",", "evt", ".", "clientX", ",", "evt", ".", "clientY", ")", ";", "textRng", ".", "setEndPoint", "(", "startRng", ".", "compareEndPoints", "(", "'StartToStart'", ",", "rngEnd", ")", "<", "0", "?", "'EndToEnd'", ":", "'StartToStart'", ",", "rngEnd", ")", ";", "textRng", ".", "select", "(", ")", ";", "}", "}" ]
Expand the text range along with mouse move.
[ "Expand", "the", "text", "range", "along", "with", "mouse", "move", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/selection.js#L626-L642
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/selection.js
function() { if ( this._.cache.nativeSel !== undefined ) return this._.cache.nativeSel; return ( this._.cache.nativeSel = isMSSelection ? this.document.$.selection : this.document.getWindow().$.getSelection() ); }
javascript
function() { if ( this._.cache.nativeSel !== undefined ) return this._.cache.nativeSel; return ( this._.cache.nativeSel = isMSSelection ? this.document.$.selection : this.document.getWindow().$.getSelection() ); }
[ "function", "(", ")", "{", "if", "(", "this", ".", "_", ".", "cache", ".", "nativeSel", "!==", "undefined", ")", "return", "this", ".", "_", ".", "cache", ".", "nativeSel", ";", "return", "(", "this", ".", "_", ".", "cache", ".", "nativeSel", "=", "isMSSelection", "?", "this", ".", "document", ".", "$", ".", "selection", ":", "this", ".", "document", ".", "getWindow", "(", ")", ".", "$", ".", "getSelection", "(", ")", ")", ";", "}" ]
Gets the native selection object from the browser. var selection = editor.getSelection().getNative(); @returns {Object} The native browser selection object.
[ "Gets", "the", "native", "selection", "object", "from", "the", "browser", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/selection.js#L1210-L1215
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/selection.js
function() { var range = self.getRanges()[ 0 ].clone(), enclosed, selected; // Check first any enclosed element, e.g. <ul>[<li><a href="#">item</a></li>]</ul> for ( var i = 2; i && !( ( enclosed = range.getEnclosedNode() ) && ( enclosed.type == CKEDITOR.NODE_ELEMENT ) && styleObjectElements[ enclosed.getName() ] && ( selected = enclosed ) ); i-- ) { // Then check any deep wrapped element, e.g. [<b><i><img /></i></b>] range.shrink( CKEDITOR.SHRINK_ELEMENT ); } return selected && selected.$; }
javascript
function() { var range = self.getRanges()[ 0 ].clone(), enclosed, selected; // Check first any enclosed element, e.g. <ul>[<li><a href="#">item</a></li>]</ul> for ( var i = 2; i && !( ( enclosed = range.getEnclosedNode() ) && ( enclosed.type == CKEDITOR.NODE_ELEMENT ) && styleObjectElements[ enclosed.getName() ] && ( selected = enclosed ) ); i-- ) { // Then check any deep wrapped element, e.g. [<b><i><img /></i></b>] range.shrink( CKEDITOR.SHRINK_ELEMENT ); } return selected && selected.$; }
[ "function", "(", ")", "{", "var", "range", "=", "self", ".", "getRanges", "(", ")", "[", "0", "]", ".", "clone", "(", ")", ",", "enclosed", ",", "selected", ";", "for", "(", "var", "i", "=", "2", ";", "i", "&&", "!", "(", "(", "enclosed", "=", "range", ".", "getEnclosedNode", "(", ")", ")", "&&", "(", "enclosed", ".", "type", "==", "CKEDITOR", ".", "NODE_ELEMENT", ")", "&&", "styleObjectElements", "[", "enclosed", ".", "getName", "(", ")", "]", "&&", "(", "selected", "=", "enclosed", ")", ")", ";", "i", "--", ")", "{", "range", ".", "shrink", "(", "CKEDITOR", ".", "SHRINK_ELEMENT", ")", ";", "}", "return", "selected", "&&", "selected", ".", "$", ";", "}" ]
Figure it out by checking if there's a single enclosed node of the range.
[ "Figure", "it", "out", "by", "checking", "if", "there", "s", "a", "single", "enclosed", "node", "of", "the", "range", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/selection.js#L1603-L1614
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/selection.js
function() { this._.cache = {}; this.isFake = 0; var editor = this.root.editor; // Invalidate any fake selection available in the editor. if ( editor && editor._.fakeSelection ) { // Test whether this selection is the one that was // faked or its clone. if ( this.rev == editor._.fakeSelection.rev ) { delete editor._.fakeSelection; removeHiddenSelectionContainer( editor ); } // jshint ignore:start // TODO after #9786 use commented out lines instead of console.log. else { // %REMOVE_LINE% window.console && console.log( 'Wrong selection instance resets fake selection.' ); // %REMOVE_LINE% } // %REMOVE_LINE% // else // %REMOVE_LINE% // CKEDITOR.debug.error( 'Wrong selection instance resets fake selection.', CKEDITOR.DEBUG_CRITICAL ); // %REMOVE_LINE% // jshint ignore:end } this.rev = nextRev++; }
javascript
function() { this._.cache = {}; this.isFake = 0; var editor = this.root.editor; // Invalidate any fake selection available in the editor. if ( editor && editor._.fakeSelection ) { // Test whether this selection is the one that was // faked or its clone. if ( this.rev == editor._.fakeSelection.rev ) { delete editor._.fakeSelection; removeHiddenSelectionContainer( editor ); } // jshint ignore:start // TODO after #9786 use commented out lines instead of console.log. else { // %REMOVE_LINE% window.console && console.log( 'Wrong selection instance resets fake selection.' ); // %REMOVE_LINE% } // %REMOVE_LINE% // else // %REMOVE_LINE% // CKEDITOR.debug.error( 'Wrong selection instance resets fake selection.', CKEDITOR.DEBUG_CRITICAL ); // %REMOVE_LINE% // jshint ignore:end } this.rev = nextRev++; }
[ "function", "(", ")", "{", "this", ".", "_", ".", "cache", "=", "{", "}", ";", "this", ".", "isFake", "=", "0", ";", "var", "editor", "=", "this", ".", "root", ".", "editor", ";", "if", "(", "editor", "&&", "editor", ".", "_", ".", "fakeSelection", ")", "{", "if", "(", "this", ".", "rev", "==", "editor", ".", "_", ".", "fakeSelection", ".", "rev", ")", "{", "delete", "editor", ".", "_", ".", "fakeSelection", ";", "removeHiddenSelectionContainer", "(", "editor", ")", ";", "}", "else", "{", "window", ".", "console", "&&", "console", ".", "log", "(", "'Wrong selection instance resets fake selection.'", ")", ";", "}", "}", "this", ".", "rev", "=", "nextRev", "++", ";", "}" ]
Clears the selection cache. editor.getSelection().reset();
[ "Clears", "the", "selection", "cache", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/selection.js#L1697-L1723
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/selection.js
function( element ) { var editor = this.root.editor; // Cleanup after previous selection - e.g. remove hidden sel container. this.reset(); hideSelection( editor ); // Set this value after executing hiseSelection, because it may // cause reset() which overwrites cache. var cache = this._.cache; // Caches a range than holds the element. var range = new CKEDITOR.dom.range( this.root ); range.setStartBefore( element ); range.setEndAfter( element ); cache.ranges = new CKEDITOR.dom.rangeList( range ); // Put this element in the cache. cache.selectedElement = cache.startElement = element; cache.type = CKEDITOR.SELECTION_ELEMENT; // Properties that will not be available when isFake. cache.selectedText = cache.nativeSel = null; this.isFake = 1; this.rev = nextRev++; // Save this selection, so it can be returned by editor.getSelection(). editor._.fakeSelection = this; // Fire selectionchange, just like a normal selection. this.root.fire( 'selectionchange' ); }
javascript
function( element ) { var editor = this.root.editor; // Cleanup after previous selection - e.g. remove hidden sel container. this.reset(); hideSelection( editor ); // Set this value after executing hiseSelection, because it may // cause reset() which overwrites cache. var cache = this._.cache; // Caches a range than holds the element. var range = new CKEDITOR.dom.range( this.root ); range.setStartBefore( element ); range.setEndAfter( element ); cache.ranges = new CKEDITOR.dom.rangeList( range ); // Put this element in the cache. cache.selectedElement = cache.startElement = element; cache.type = CKEDITOR.SELECTION_ELEMENT; // Properties that will not be available when isFake. cache.selectedText = cache.nativeSel = null; this.isFake = 1; this.rev = nextRev++; // Save this selection, so it can be returned by editor.getSelection(). editor._.fakeSelection = this; // Fire selectionchange, just like a normal selection. this.root.fire( 'selectionchange' ); }
[ "function", "(", "element", ")", "{", "var", "editor", "=", "this", ".", "root", ".", "editor", ";", "this", ".", "reset", "(", ")", ";", "hideSelection", "(", "editor", ")", ";", "var", "cache", "=", "this", ".", "_", ".", "cache", ";", "var", "range", "=", "new", "CKEDITOR", ".", "dom", ".", "range", "(", "this", ".", "root", ")", ";", "range", ".", "setStartBefore", "(", "element", ")", ";", "range", ".", "setEndAfter", "(", "element", ")", ";", "cache", ".", "ranges", "=", "new", "CKEDITOR", ".", "dom", ".", "rangeList", "(", "range", ")", ";", "cache", ".", "selectedElement", "=", "cache", ".", "startElement", "=", "element", ";", "cache", ".", "type", "=", "CKEDITOR", ".", "SELECTION_ELEMENT", ";", "cache", ".", "selectedText", "=", "cache", ".", "nativeSel", "=", "null", ";", "this", ".", "isFake", "=", "1", ";", "this", ".", "rev", "=", "nextRev", "++", ";", "editor", ".", "_", ".", "fakeSelection", "=", "this", ";", "this", ".", "root", ".", "fire", "(", "'selectionchange'", ")", ";", "}" ]
Makes a "fake selection" of an element. A fake selection does not render UI artifacts over the selected element. Additionally, the browser native selection system is not aware of the fake selection. In practice, the native selection is moved to a hidden place where no native selection UI artifacts are displayed to the user. @param {CKEDITOR.dom.element} element The element to be "selected".
[ "Makes", "a", "fake", "selection", "of", "an", "element", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/selection.js#L2001-L2034
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/selection.js
function() { var el = this.getCommonAncestor(); if ( el && el.type == CKEDITOR.NODE_TEXT ) el = el.getParent(); return !!( el && el.data( 'cke-hidden-sel' ) ); }
javascript
function() { var el = this.getCommonAncestor(); if ( el && el.type == CKEDITOR.NODE_TEXT ) el = el.getParent(); return !!( el && el.data( 'cke-hidden-sel' ) ); }
[ "function", "(", ")", "{", "var", "el", "=", "this", ".", "getCommonAncestor", "(", ")", ";", "if", "(", "el", "&&", "el", ".", "type", "==", "CKEDITOR", ".", "NODE_TEXT", ")", "el", "=", "el", ".", "getParent", "(", ")", ";", "return", "!", "!", "(", "el", "&&", "el", ".", "data", "(", "'cke-hidden-sel'", ")", ")", ";", "}" ]
Checks whether selection is placed in hidden element. This method is to be used to verify whether fake selection (see {@link #fake}) is still hidden. **Note:** this method should be executed on real selection - e.g.: editor.getSelection( true ).isHidden(); @returns {Boolean}
[ "Checks", "whether", "selection", "is", "placed", "in", "hidden", "element", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/selection.js#L2048-L2055
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/selection.js
function() { // Don't clear selection outside this selection's root (#11500). if ( this.getType() == CKEDITOR.SELECTION_NONE ) return; var nativ = this.getNative(); try { nativ && nativ[ isMSSelection ? 'empty' : 'removeAllRanges' ](); } catch ( er ) {} this.reset(); }
javascript
function() { // Don't clear selection outside this selection's root (#11500). if ( this.getType() == CKEDITOR.SELECTION_NONE ) return; var nativ = this.getNative(); try { nativ && nativ[ isMSSelection ? 'empty' : 'removeAllRanges' ](); } catch ( er ) {} this.reset(); }
[ "function", "(", ")", "{", "if", "(", "this", ".", "getType", "(", ")", "==", "CKEDITOR", ".", "SELECTION_NONE", ")", "return", ";", "var", "nativ", "=", "this", ".", "getNative", "(", ")", ";", "try", "{", "nativ", "&&", "nativ", "[", "isMSSelection", "?", "'empty'", ":", "'removeAllRanges'", "]", "(", ")", ";", "}", "catch", "(", "er", ")", "{", "}", "this", ".", "reset", "(", ")", ";", "}" ]
Remove all the selection ranges from the document.
[ "Remove", "all", "the", "selection", "ranges", "from", "the", "document", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/selection.js#L2145-L2157
train
openplacedatabase/opd-js-sdk
src/sdk.js
_multiCallback
function _multiCallback(serverError, serverResponse, callback, interleave, requestedIds){ var clientResponse = {}; // Handle response errors _.each(serverResponse, function(data, id){ var thisError = serverError; if(serverError && data.status.code !== 200){ thisError = new Error(data.status.msgs.join('. ')); thisError.code = data.status.code; } clientResponse[id] = { error: thisError, data: data.data }; }); // Handle request level errors if(serverError && !serverResponse){ _.each(requestedIds, function(id){ if(_.isUndefined(clientResponse[id])){ clientResponse[id] = { error: serverError, data: null }; } }); } // Interleave validation errors if(interleave){ _.extend(clientResponse, interleave); } callback(clientResponse); }
javascript
function _multiCallback(serverError, serverResponse, callback, interleave, requestedIds){ var clientResponse = {}; // Handle response errors _.each(serverResponse, function(data, id){ var thisError = serverError; if(serverError && data.status.code !== 200){ thisError = new Error(data.status.msgs.join('. ')); thisError.code = data.status.code; } clientResponse[id] = { error: thisError, data: data.data }; }); // Handle request level errors if(serverError && !serverResponse){ _.each(requestedIds, function(id){ if(_.isUndefined(clientResponse[id])){ clientResponse[id] = { error: serverError, data: null }; } }); } // Interleave validation errors if(interleave){ _.extend(clientResponse, interleave); } callback(clientResponse); }
[ "function", "_multiCallback", "(", "serverError", ",", "serverResponse", ",", "callback", ",", "interleave", ",", "requestedIds", ")", "{", "var", "clientResponse", "=", "{", "}", ";", "_", ".", "each", "(", "serverResponse", ",", "function", "(", "data", ",", "id", ")", "{", "var", "thisError", "=", "serverError", ";", "if", "(", "serverError", "&&", "data", ".", "status", ".", "code", "!==", "200", ")", "{", "thisError", "=", "new", "Error", "(", "data", ".", "status", ".", "msgs", ".", "join", "(", "'. '", ")", ")", ";", "thisError", ".", "code", "=", "data", ".", "status", ".", "code", ";", "}", "clientResponse", "[", "id", "]", "=", "{", "error", ":", "thisError", ",", "data", ":", "data", ".", "data", "}", ";", "}", ")", ";", "if", "(", "serverError", "&&", "!", "serverResponse", ")", "{", "_", ".", "each", "(", "requestedIds", ",", "function", "(", "id", ")", "{", "if", "(", "_", ".", "isUndefined", "(", "clientResponse", "[", "id", "]", ")", ")", "{", "clientResponse", "[", "id", "]", "=", "{", "error", ":", "serverError", ",", "data", ":", "null", "}", ";", "}", "}", ")", ";", "}", "if", "(", "interleave", ")", "{", "_", ".", "extend", "(", "clientResponse", ",", "interleave", ")", ";", "}", "callback", "(", "clientResponse", ")", ";", "}" ]
Callback used by Multi methods that generates the proper response format
[ "Callback", "used", "by", "Multi", "methods", "that", "generates", "the", "proper", "response", "format" ]
e64eb079cc76af5a5acff27a7614ffb70f0b7e33
https://github.com/openplacedatabase/opd-js-sdk/blob/e64eb079cc76af5a5acff27a7614ffb70f0b7e33/src/sdk.js#L195-L229
train
dashed/providence
src/index.js
Providence
function Providence(options = NOT_SET, skipDataCheck = false, skipProcessOptions = false) { if(options === NOT_SET) { throw new Error('Expected options to be a plain object or an Immutable Map'); } // This will not support constructors that are extending Providence. // They should provide their own setup in their constructor function. if(!(this instanceof Providence)) { return new Providence(options, skipDataCheck, skipProcessOptions); } this._options = skipProcessOptions ? options : processOptions(options); // Used for caching value of the Providence object. // When the unboxed root data and this._refUnboxedRootData are equal, // then unboxed root data hasn't changed since the previous look up, and thus // this._cachedValue and value at path also hasn't changed. this._refUnboxedRootData = NOT_SET; this._cachedValue = NOT_SET; if(!skipDataCheck && this._options.getIn(DATA_PATH, NOT_SET) === NOT_SET) { throw new Error("value at path ['root', 'data'] is required!") } }
javascript
function Providence(options = NOT_SET, skipDataCheck = false, skipProcessOptions = false) { if(options === NOT_SET) { throw new Error('Expected options to be a plain object or an Immutable Map'); } // This will not support constructors that are extending Providence. // They should provide their own setup in their constructor function. if(!(this instanceof Providence)) { return new Providence(options, skipDataCheck, skipProcessOptions); } this._options = skipProcessOptions ? options : processOptions(options); // Used for caching value of the Providence object. // When the unboxed root data and this._refUnboxedRootData are equal, // then unboxed root data hasn't changed since the previous look up, and thus // this._cachedValue and value at path also hasn't changed. this._refUnboxedRootData = NOT_SET; this._cachedValue = NOT_SET; if(!skipDataCheck && this._options.getIn(DATA_PATH, NOT_SET) === NOT_SET) { throw new Error("value at path ['root', 'data'] is required!") } }
[ "function", "Providence", "(", "options", "=", "NOT_SET", ",", "skipDataCheck", "=", "false", ",", "skipProcessOptions", "=", "false", ")", "{", "if", "(", "options", "===", "NOT_SET", ")", "{", "throw", "new", "Error", "(", "'Expected options to be a plain object or an Immutable Map'", ")", ";", "}", "if", "(", "!", "(", "this", "instanceof", "Providence", ")", ")", "{", "return", "new", "Providence", "(", "options", ",", "skipDataCheck", ",", "skipProcessOptions", ")", ";", "}", "this", ".", "_options", "=", "skipProcessOptions", "?", "options", ":", "processOptions", "(", "options", ")", ";", "this", ".", "_refUnboxedRootData", "=", "NOT_SET", ";", "this", ".", "_cachedValue", "=", "NOT_SET", ";", "if", "(", "!", "skipDataCheck", "&&", "this", ".", "_options", ".", "getIn", "(", "DATA_PATH", ",", "NOT_SET", ")", "===", "NOT_SET", ")", "{", "throw", "new", "Error", "(", "\"value at path ['root', 'data'] is required!\"", ")", "}", "}" ]
Create a Providence cursor given options. Options may either be plain object or an Immutable Map. @param {Object | Immutable Map} options Defines the character of the providence cursor.
[ "Create", "a", "Providence", "cursor", "given", "options", ".", "Options", "may", "either", "be", "plain", "object", "or", "an", "Immutable", "Map", "." ]
8e0e5631e092b11f1fd8500c634523a231aec00f
https://github.com/dashed/providence/blob/8e0e5631e092b11f1fd8500c634523a231aec00f/src/index.js#L66-L90
train
kaelzhang/node-cobj
index.js
_set
function _set (data, keys, value) { var i = 0; var prop; var length = keys.length; for(; i < length; i ++){ prop = keys[i]; if (i === length - 1) { // if the last key, set value data[prop] = value; return; } if ( !(prop in data) // If the current value is not an object, we will override it. // The logic who invoke `.set()` method should make sure `data[prop]` is an object, // which `.set()` doesn't concern || !is_object(data[prop]) ) { data[prop] = {}; } data = data[prop]; } }
javascript
function _set (data, keys, value) { var i = 0; var prop; var length = keys.length; for(; i < length; i ++){ prop = keys[i]; if (i === length - 1) { // if the last key, set value data[prop] = value; return; } if ( !(prop in data) // If the current value is not an object, we will override it. // The logic who invoke `.set()` method should make sure `data[prop]` is an object, // which `.set()` doesn't concern || !is_object(data[prop]) ) { data[prop] = {}; } data = data[prop]; } }
[ "function", "_set", "(", "data", ",", "keys", ",", "value", ")", "{", "var", "i", "=", "0", ";", "var", "prop", ";", "var", "length", "=", "keys", ".", "length", ";", "for", "(", ";", "i", "<", "length", ";", "i", "++", ")", "{", "prop", "=", "keys", "[", "i", "]", ";", "if", "(", "i", "===", "length", "-", "1", ")", "{", "data", "[", "prop", "]", "=", "value", ";", "return", ";", "}", "if", "(", "!", "(", "prop", "in", "data", ")", "||", "!", "is_object", "(", "data", "[", "prop", "]", ")", ")", "{", "data", "[", "prop", "]", "=", "{", "}", ";", "}", "data", "=", "data", "[", "prop", "]", ";", "}", "}" ]
For better testing
[ "For", "better", "testing" ]
ced3c8031f3a6f69ae151bceba3ccb85dcab2f9e
https://github.com/kaelzhang/node-cobj/blob/ced3c8031f3a6f69ae151bceba3ccb85dcab2f9e/index.js#L69-L94
train
mcrowe/channel
lib/util.js
pull
function pull(xs, x) { const idx = xs.indexOf(x); if (idx > -1) { xs.splice(idx, 1); } }
javascript
function pull(xs, x) { const idx = xs.indexOf(x); if (idx > -1) { xs.splice(idx, 1); } }
[ "function", "pull", "(", "xs", ",", "x", ")", "{", "const", "idx", "=", "xs", ".", "indexOf", "(", "x", ")", ";", "if", "(", "idx", ">", "-", "1", ")", "{", "xs", ".", "splice", "(", "idx", ",", "1", ")", ";", "}", "}" ]
Remove an item from a list, in place.
[ "Remove", "an", "item", "from", "a", "list", "in", "place", "." ]
b1cf88f8b614d902b91923329fdac5cae8458b2d
https://github.com/mcrowe/channel/blob/b1cf88f8b614d902b91923329fdac5cae8458b2d/lib/util.js#L6-L11
train
cliffano/pkjutil
lib/cli.js
exec
function exec() { var actions = { commands: { 'list-dependencies': { action: _listDependencies }, 'list-devdependencies': { action: _listDevDependencies }, 'list-peerdependencies': { action: _listPeerDependencies }, 'list-optdependencies': { action: _listOptDependencies }, 'list-alldependencies': { action: _listAllDependencies }, 'set-node-engine': { action: _setNodeEngine }, 'sort-dependencies': { action: _sortDependencies }, 'sort-devdependencies': { action: _sortDevDependencies }, 'sort-peerdependencies': { action: _sortPeerDependencies }, 'sort-optdependencies': { action: _sortOptDependencies }, 'sort-alldependencies': { action: _sortAllDependencies }, 'traverse-dependencies': { action: _traverseDependencies }, 'upgrade-version-patch': { action: _upgradeVersionPatch }, 'upgrade-version-minor': { action: _upgradeVersionMinor }, 'upgrade-version-major': { action: _upgradeVersionMajor }, 'upgrade-version': { action: _upgradeVersionPatch }, 'upgrade-dependencies': { action: _upgradeDependencies }, } }; cli.command(__dirname, actions); }
javascript
function exec() { var actions = { commands: { 'list-dependencies': { action: _listDependencies }, 'list-devdependencies': { action: _listDevDependencies }, 'list-peerdependencies': { action: _listPeerDependencies }, 'list-optdependencies': { action: _listOptDependencies }, 'list-alldependencies': { action: _listAllDependencies }, 'set-node-engine': { action: _setNodeEngine }, 'sort-dependencies': { action: _sortDependencies }, 'sort-devdependencies': { action: _sortDevDependencies }, 'sort-peerdependencies': { action: _sortPeerDependencies }, 'sort-optdependencies': { action: _sortOptDependencies }, 'sort-alldependencies': { action: _sortAllDependencies }, 'traverse-dependencies': { action: _traverseDependencies }, 'upgrade-version-patch': { action: _upgradeVersionPatch }, 'upgrade-version-minor': { action: _upgradeVersionMinor }, 'upgrade-version-major': { action: _upgradeVersionMajor }, 'upgrade-version': { action: _upgradeVersionPatch }, 'upgrade-dependencies': { action: _upgradeDependencies }, } }; cli.command(__dirname, actions); }
[ "function", "exec", "(", ")", "{", "var", "actions", "=", "{", "commands", ":", "{", "'list-dependencies'", ":", "{", "action", ":", "_listDependencies", "}", ",", "'list-devdependencies'", ":", "{", "action", ":", "_listDevDependencies", "}", ",", "'list-peerdependencies'", ":", "{", "action", ":", "_listPeerDependencies", "}", ",", "'list-optdependencies'", ":", "{", "action", ":", "_listOptDependencies", "}", ",", "'list-alldependencies'", ":", "{", "action", ":", "_listAllDependencies", "}", ",", "'set-node-engine'", ":", "{", "action", ":", "_setNodeEngine", "}", ",", "'sort-dependencies'", ":", "{", "action", ":", "_sortDependencies", "}", ",", "'sort-devdependencies'", ":", "{", "action", ":", "_sortDevDependencies", "}", ",", "'sort-peerdependencies'", ":", "{", "action", ":", "_sortPeerDependencies", "}", ",", "'sort-optdependencies'", ":", "{", "action", ":", "_sortOptDependencies", "}", ",", "'sort-alldependencies'", ":", "{", "action", ":", "_sortAllDependencies", "}", ",", "'traverse-dependencies'", ":", "{", "action", ":", "_traverseDependencies", "}", ",", "'upgrade-version-patch'", ":", "{", "action", ":", "_upgradeVersionPatch", "}", ",", "'upgrade-version-minor'", ":", "{", "action", ":", "_upgradeVersionMinor", "}", ",", "'upgrade-version-major'", ":", "{", "action", ":", "_upgradeVersionMajor", "}", ",", "'upgrade-version'", ":", "{", "action", ":", "_upgradeVersionPatch", "}", ",", "'upgrade-dependencies'", ":", "{", "action", ":", "_upgradeDependencies", "}", ",", "}", "}", ";", "cli", ".", "command", "(", "__dirname", ",", "actions", ")", ";", "}" ]
Execute PkjUtil CLI.
[ "Execute", "PkjUtil", "CLI", "." ]
8c6d69bf375619da0ee0a1a031312a3f20d53fcf
https://github.com/cliffano/pkjutil/blob/8c6d69bf375619da0ee0a1a031312a3f20d53fcf/lib/cli.js#L111-L136
train
pmh/espresso
lib/ometa/ometa/ometa.js
cached
function cached(grammar_file) { var fs = require('fs'), path = require('path'), change = fs.statSync(grammar_file).mtime.valueOf(), cache = [cache_path,'/', path.basename(grammar_file), '.', change, '.js'].join(''); if(!fs.existsSync(cache_path)) fs.mkdirSync(cache_path); if(fs.existsSync(cache)) return fs.readFileSync(cache, 'utf8'); var result = load(grammar_file); fs.writeFileSync(cache, result); return result; }
javascript
function cached(grammar_file) { var fs = require('fs'), path = require('path'), change = fs.statSync(grammar_file).mtime.valueOf(), cache = [cache_path,'/', path.basename(grammar_file), '.', change, '.js'].join(''); if(!fs.existsSync(cache_path)) fs.mkdirSync(cache_path); if(fs.existsSync(cache)) return fs.readFileSync(cache, 'utf8'); var result = load(grammar_file); fs.writeFileSync(cache, result); return result; }
[ "function", "cached", "(", "grammar_file", ")", "{", "var", "fs", "=", "require", "(", "'fs'", ")", ",", "path", "=", "require", "(", "'path'", ")", ",", "change", "=", "fs", ".", "statSync", "(", "grammar_file", ")", ".", "mtime", ".", "valueOf", "(", ")", ",", "cache", "=", "[", "cache_path", ",", "'/'", ",", "path", ".", "basename", "(", "grammar_file", ")", ",", "'.'", ",", "change", ",", "'.js'", "]", ".", "join", "(", "''", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "cache_path", ")", ")", "fs", ".", "mkdirSync", "(", "cache_path", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "cache", ")", ")", "return", "fs", ".", "readFileSync", "(", "cache", ",", "'utf8'", ")", ";", "var", "result", "=", "load", "(", "grammar_file", ")", ";", "fs", ".", "writeFileSync", "(", "cache", ",", "result", ")", ";", "return", "result", ";", "}" ]
Internal function to cache grammars. Creates a `.cache` directory in the current working path.
[ "Internal", "function", "to", "cache", "grammars", ".", "Creates", "a", ".", "cache", "directory", "in", "the", "current", "working", "path", "." ]
26d7b2089a2098344aaaf32ec7eb942e91a7edf5
https://github.com/pmh/espresso/blob/26d7b2089a2098344aaaf32ec7eb942e91a7edf5/lib/ometa/ometa/ometa.js#L8-L23
train
pmh/espresso
lib/ometa/ometa/ometa.js
load
function load(grammar_file) { var fs = require('fs'), grammar = fs.readFileSync(grammar_file, 'utf-8'); return compile(grammar) }
javascript
function load(grammar_file) { var fs = require('fs'), grammar = fs.readFileSync(grammar_file, 'utf-8'); return compile(grammar) }
[ "function", "load", "(", "grammar_file", ")", "{", "var", "fs", "=", "require", "(", "'fs'", ")", ",", "grammar", "=", "fs", ".", "readFileSync", "(", "grammar_file", ",", "'utf-8'", ")", ";", "return", "compile", "(", "grammar", ")", "}" ]
Loads the specified grammar file and returns the generated grammar JavaScript code for it. Evaling this code in your module will create the grammar objects in the global module namespace.
[ "Loads", "the", "specified", "grammar", "file", "and", "returns", "the", "generated", "grammar", "JavaScript", "code", "for", "it", ".", "Evaling", "this", "code", "in", "your", "module", "will", "create", "the", "grammar", "objects", "in", "the", "global", "module", "namespace", "." ]
26d7b2089a2098344aaaf32ec7eb942e91a7edf5
https://github.com/pmh/espresso/blob/26d7b2089a2098344aaaf32ec7eb942e91a7edf5/lib/ometa/ometa/ometa.js#L30-L34
train
pmh/espresso
lib/ometa/ometa/ometa.js
run
function run(grammar, module, filename) { // this is used to bind OMeta to runtime. It can be used also (lateron) to dynamically // inject other environment-variables. // {a:1,b:2,c:3,d:4} -> function(a,b,c,d) {...}.call(1,2,3,4) // this is better than `with`, since it offers full control var source = [ "module.grammar = (function(OMeta) {", grammar, "});" ].join(''); module._compile(source, filename); module.grammar.call(module, ometa); return module.exports; }
javascript
function run(grammar, module, filename) { // this is used to bind OMeta to runtime. It can be used also (lateron) to dynamically // inject other environment-variables. // {a:1,b:2,c:3,d:4} -> function(a,b,c,d) {...}.call(1,2,3,4) // this is better than `with`, since it offers full control var source = [ "module.grammar = (function(OMeta) {", grammar, "});" ].join(''); module._compile(source, filename); module.grammar.call(module, ometa); return module.exports; }
[ "function", "run", "(", "grammar", ",", "module", ",", "filename", ")", "{", "var", "source", "=", "[", "\"module.grammar = (function(OMeta) {\"", ",", "grammar", ",", "\"});\"", "]", ".", "join", "(", "''", ")", ";", "module", ".", "_compile", "(", "source", ",", "filename", ")", ";", "module", ".", "grammar", ".", "call", "(", "module", ",", "ometa", ")", ";", "return", "module", ".", "exports", ";", "}" ]
Evaluates the grammar-module and returns the exports of that module
[ "Evaluates", "the", "grammar", "-", "module", "and", "returns", "the", "exports", "of", "that", "module" ]
26d7b2089a2098344aaaf32ec7eb942e91a7edf5
https://github.com/pmh/espresso/blob/26d7b2089a2098344aaaf32ec7eb942e91a7edf5/lib/ometa/ometa/ometa.js#L50-L65
train
torworx/well
function.js
_apply
function _apply(func, thisArg, promisedArgs) { return well.all(promisedArgs || []).then(function(args) { return func.apply(thisArg, args); }); }
javascript
function _apply(func, thisArg, promisedArgs) { return well.all(promisedArgs || []).then(function(args) { return func.apply(thisArg, args); }); }
[ "function", "_apply", "(", "func", ",", "thisArg", ",", "promisedArgs", ")", "{", "return", "well", ".", "all", "(", "promisedArgs", "||", "[", "]", ")", ".", "then", "(", "function", "(", "args", ")", "{", "return", "func", ".", "apply", "(", "thisArg", ",", "args", ")", ";", "}", ")", ";", "}" ]
Apply helper that allows specifying thisArg @private
[ "Apply", "helper", "that", "allows", "specifying", "thisArg" ]
45a1724a0a4192628c80b3c4ae541d6de28ac7da
https://github.com/torworx/well/blob/45a1724a0a4192628c80b3c4ae541d6de28ac7da/function.js#L59-L63
train
torworx/well
function.js
lift
function lift(func /*, args... */) { var args = slice.call(arguments, 1); return function() { return _apply(func, this, args.concat(slice.call(arguments))); }; }
javascript
function lift(func /*, args... */) { var args = slice.call(arguments, 1); return function() { return _apply(func, this, args.concat(slice.call(arguments))); }; }
[ "function", "lift", "(", "func", ")", "{", "var", "args", "=", "slice", ".", "call", "(", "arguments", ",", "1", ")", ";", "return", "function", "(", ")", "{", "return", "_apply", "(", "func", ",", "this", ",", "args", ".", "concat", "(", "slice", ".", "call", "(", "arguments", ")", ")", ")", ";", "}", ";", "}" ]
Takes a 'regular' function and returns a version of that function that returns a promise instead of a plain value, and handles thrown errors by returning a rejected promise. Also accepts a list of arguments to be prepended to the new function, as does Function.prototype.bind. The resulting function is promise-aware, in the sense that it accepts promise arguments, and waits for their resolution. @example function mayThrowError(n) { if(n % 2 === 1) { // Normally this wouldn't be so deterministic :) throw new Error("I don't like odd numbers"); } else { return n; } } var lifted = fn.lift(mayThrowError); // Logs "I don't like odd numbers" lifted(1).then(console.log, console.error); // Logs '6' lifted(6).then(console.log, console.error); @example function sumTwoNumbers(x, y) { return x + y; } var sumWithFive = fn.lifted(sumTwoNumbers, 5); // Logs '15' sumWithFive(10).then(console.log, console.error); @param {Function} func function to be bound @param {...*} [args] arguments to be prepended for the new function @returns {Function} a promise-returning function
[ "Takes", "a", "regular", "function", "and", "returns", "a", "version", "of", "that", "function", "that", "returns", "a", "promise", "instead", "of", "a", "plain", "value", "and", "handles", "thrown", "errors", "by", "returning", "a", "rejected", "promise", ".", "Also", "accepts", "a", "list", "of", "arguments", "to", "be", "prepended", "to", "the", "new", "function", "as", "does", "Function", ".", "prototype", ".", "bind", "." ]
45a1724a0a4192628c80b3c4ae541d6de28ac7da
https://github.com/torworx/well/blob/45a1724a0a4192628c80b3c4ae541d6de28ac7da/function.js#L133-L138
train
camshaft/pack-n-stack
lib/stack.js
createStack
function createStack(app) { if (!app) { throw new Error("Pack-n-stack requires an express/connect app"); }; app = utils.merge(app, proto); Object.defineProperty(app, "count", { get: function() { return app.stack.length; } }); return app; }
javascript
function createStack(app) { if (!app) { throw new Error("Pack-n-stack requires an express/connect app"); }; app = utils.merge(app, proto); Object.defineProperty(app, "count", { get: function() { return app.stack.length; } }); return app; }
[ "function", "createStack", "(", "app", ")", "{", "if", "(", "!", "app", ")", "{", "throw", "new", "Error", "(", "\"Pack-n-stack requires an express/connect app\"", ")", ";", "}", ";", "app", "=", "utils", ".", "merge", "(", "app", ",", "proto", ")", ";", "Object", ".", "defineProperty", "(", "app", ",", "\"count\"", ",", "{", "get", ":", "function", "(", ")", "{", "return", "app", ".", "stack", ".", "length", ";", "}", "}", ")", ";", "return", "app", ";", "}" ]
Create a new stack. @return {Function} @api public
[ "Create", "a", "new", "stack", "." ]
ec5fe9a4cb9895b89e137e966a4eaffb7931881c
https://github.com/camshaft/pack-n-stack/blob/ec5fe9a4cb9895b89e137e966a4eaffb7931881c/lib/stack.js#L29-L43
train
dggriffin/mitto
lib/index.js
loadConfig
function loadConfig(filename) { //Does our consumer have a valid .mitto? var mittoObject = _loadMitto(); //Is it in a valid format? mittoObject = _validateMitto(mittoObject); //Does our consumer's consumer have a config of 'filename'? var configObject = _findFile(filename); //Is it in a valid format as prescribed by our consumer's .mitto? return _validateConfig(configObject, mittoObject); }
javascript
function loadConfig(filename) { //Does our consumer have a valid .mitto? var mittoObject = _loadMitto(); //Is it in a valid format? mittoObject = _validateMitto(mittoObject); //Does our consumer's consumer have a config of 'filename'? var configObject = _findFile(filename); //Is it in a valid format as prescribed by our consumer's .mitto? return _validateConfig(configObject, mittoObject); }
[ "function", "loadConfig", "(", "filename", ")", "{", "var", "mittoObject", "=", "_loadMitto", "(", ")", ";", "mittoObject", "=", "_validateMitto", "(", "mittoObject", ")", ";", "var", "configObject", "=", "_findFile", "(", "filename", ")", ";", "return", "_validateConfig", "(", "configObject", ",", "mittoObject", ")", ";", "}" ]
Find JSON configuration given a filename Applies .mitto constraints if your package has a .mitto package present @return {json converted to Object}
[ "Find", "JSON", "configuration", "given", "a", "filename", "Applies", ".", "mitto", "constraints", "if", "your", "package", "has", "a", ".", "mitto", "package", "present" ]
a58cd439b67b626522078b8003a82a348103a66c
https://github.com/dggriffin/mitto/blob/a58cd439b67b626522078b8003a82a348103a66c/lib/index.js#L28-L38
train
dggriffin/mitto
lib/index.js
_findFile
function _findFile(filename) { var cwd = process.cwd(); var parts = cwd.split(_path2.default.sep); do { var loc = parts.join(_path2.default.sep); if (!loc) break; var file = _path2.default.join(loc, filename); if (_fs2.default.existsSync(file)) { var fileObj = undefined; try { fileObj = require(file); } catch (e) { fileObj = _loadJSON(file); } return fileObj; } parts.pop(); } while (parts.length); return null; }
javascript
function _findFile(filename) { var cwd = process.cwd(); var parts = cwd.split(_path2.default.sep); do { var loc = parts.join(_path2.default.sep); if (!loc) break; var file = _path2.default.join(loc, filename); if (_fs2.default.existsSync(file)) { var fileObj = undefined; try { fileObj = require(file); } catch (e) { fileObj = _loadJSON(file); } return fileObj; } parts.pop(); } while (parts.length); return null; }
[ "function", "_findFile", "(", "filename", ")", "{", "var", "cwd", "=", "process", ".", "cwd", "(", ")", ";", "var", "parts", "=", "cwd", ".", "split", "(", "_path2", ".", "default", ".", "sep", ")", ";", "do", "{", "var", "loc", "=", "parts", ".", "join", "(", "_path2", ".", "default", ".", "sep", ")", ";", "if", "(", "!", "loc", ")", "break", ";", "var", "file", "=", "_path2", ".", "default", ".", "join", "(", "loc", ",", "filename", ")", ";", "if", "(", "_fs2", ".", "default", ".", "existsSync", "(", "file", ")", ")", "{", "var", "fileObj", "=", "undefined", ";", "try", "{", "fileObj", "=", "require", "(", "file", ")", ";", "}", "catch", "(", "e", ")", "{", "fileObj", "=", "_loadJSON", "(", "file", ")", ";", "}", "return", "fileObj", ";", "}", "parts", ".", "pop", "(", ")", ";", "}", "while", "(", "parts", ".", "length", ")", ";", "return", "null", ";", "}" ]
PRIVATE HELPER FUNCTIONS Find a "require" a JSON configuration given the filename
[ "PRIVATE", "HELPER", "FUNCTIONS", "Find", "a", "require", "a", "JSON", "configuration", "given", "the", "filename" ]
a58cd439b67b626522078b8003a82a348103a66c
https://github.com/dggriffin/mitto/blob/a58cd439b67b626522078b8003a82a348103a66c/lib/index.js#L45-L67
train
dggriffin/mitto
lib/index.js
_validateMitto
function _validateMitto(mittoObject) { if (!mittoObject) { return null; } if (!mittoObject.hasOwnProperty("name")) { throw new Error("\"name\" property is missing from your .mitto and is required."); } if (mittoObject.hasOwnProperty("required")) { for (var key in mittoObject.required) { if (mittoObject.required[key].hasOwnProperty("type")) { if (DATA_TYPES.indexOf(mittoObject.required[key].type) === -1) { throw new Error(mittoObject.required[key].type + " is not a valid data type. Expected: \"undefined\", \"object\", \"boolean\", \"number\", \"string\", \"symbol\", or \"function\""); } } else { throw new Error("\"type\" property is missing from your .mitto's required parameter \"" + key + "\""); } if (mittoObject.required[key].hasOwnProperty("description") && typeof mittoObject.required[key].description !== "string") { throw new Error("\"description\" property of your .mitto's required parameter " + key + " must be of type \"string\""); } } } if (mittoObject.hasOwnProperty("optional")) { for (var key in mittoObject.optional) { if (mittoObject.optional[key].hasOwnProperty("type")) { if (DATA_TYPES.indexOf(mittoObject.optional[key].type) === -1) { throw new Error(mittoObject.optional[key].type + " is not a valid data type. Expected: \"undefined\", \"object\", \"boolean\", \"number\", \"string\", \"symbol\", or \"function\""); } } else { throw new Error("\"type\" property is missing from your .mitto's optional parameter " + key); } if (mittoObject.optional[key].hasOwnProperty("description") && typeof mittoObject.optional[key].description !== "string") { throw new Error("\"description\" property of your .mitto's optional parameter " + key + " must be of type \"string\""); } if (mittoObject.optional[key].hasOwnProperty("default") && _typeof(mittoObject.optional[key].default) !== mittoObject.optional[key].type) { throw new Error("\"default\" property of your .mitto's optional parameter " + key + " must be a " + mittoObject.optional[key].type + ", as specified by \"type\""); } else if (mittoObject.optional[key].hasOwnProperty("default")) { mittoObject.hasDefault = true; } } } return mittoObject; }
javascript
function _validateMitto(mittoObject) { if (!mittoObject) { return null; } if (!mittoObject.hasOwnProperty("name")) { throw new Error("\"name\" property is missing from your .mitto and is required."); } if (mittoObject.hasOwnProperty("required")) { for (var key in mittoObject.required) { if (mittoObject.required[key].hasOwnProperty("type")) { if (DATA_TYPES.indexOf(mittoObject.required[key].type) === -1) { throw new Error(mittoObject.required[key].type + " is not a valid data type. Expected: \"undefined\", \"object\", \"boolean\", \"number\", \"string\", \"symbol\", or \"function\""); } } else { throw new Error("\"type\" property is missing from your .mitto's required parameter \"" + key + "\""); } if (mittoObject.required[key].hasOwnProperty("description") && typeof mittoObject.required[key].description !== "string") { throw new Error("\"description\" property of your .mitto's required parameter " + key + " must be of type \"string\""); } } } if (mittoObject.hasOwnProperty("optional")) { for (var key in mittoObject.optional) { if (mittoObject.optional[key].hasOwnProperty("type")) { if (DATA_TYPES.indexOf(mittoObject.optional[key].type) === -1) { throw new Error(mittoObject.optional[key].type + " is not a valid data type. Expected: \"undefined\", \"object\", \"boolean\", \"number\", \"string\", \"symbol\", or \"function\""); } } else { throw new Error("\"type\" property is missing from your .mitto's optional parameter " + key); } if (mittoObject.optional[key].hasOwnProperty("description") && typeof mittoObject.optional[key].description !== "string") { throw new Error("\"description\" property of your .mitto's optional parameter " + key + " must be of type \"string\""); } if (mittoObject.optional[key].hasOwnProperty("default") && _typeof(mittoObject.optional[key].default) !== mittoObject.optional[key].type) { throw new Error("\"default\" property of your .mitto's optional parameter " + key + " must be a " + mittoObject.optional[key].type + ", as specified by \"type\""); } else if (mittoObject.optional[key].hasOwnProperty("default")) { mittoObject.hasDefault = true; } } } return mittoObject; }
[ "function", "_validateMitto", "(", "mittoObject", ")", "{", "if", "(", "!", "mittoObject", ")", "{", "return", "null", ";", "}", "if", "(", "!", "mittoObject", ".", "hasOwnProperty", "(", "\"name\"", ")", ")", "{", "throw", "new", "Error", "(", "\"\\\"name\\\" property is missing from your .mitto and is required.\"", ")", ";", "}", "\\\"", "\\\"", "if", "(", "mittoObject", ".", "hasOwnProperty", "(", "\"required\"", ")", ")", "{", "for", "(", "var", "key", "in", "mittoObject", ".", "required", ")", "{", "if", "(", "mittoObject", ".", "required", "[", "key", "]", ".", "hasOwnProperty", "(", "\"type\"", ")", ")", "{", "if", "(", "DATA_TYPES", ".", "indexOf", "(", "mittoObject", ".", "required", "[", "key", "]", ".", "type", ")", "===", "-", "1", ")", "{", "throw", "new", "Error", "(", "mittoObject", ".", "required", "[", "key", "]", ".", "type", "+", "\" is not a valid data type. Expected: \\\"undefined\\\", \\\"object\\\", \\\"boolean\\\", \\\"number\\\", \\\"string\\\", \\\"symbol\\\", or \\\"function\\\"\"", ")", ";", "}", "}", "else", "\\\"", "\\\"", "}", "}", "}" ]
Validate .mitto object handed off to function to ensure it is syntatical correct
[ "Validate", ".", "mitto", "object", "handed", "off", "to", "function", "to", "ensure", "it", "is", "syntatical", "correct" ]
a58cd439b67b626522078b8003a82a348103a66c
https://github.com/dggriffin/mitto/blob/a58cd439b67b626522078b8003a82a348103a66c/lib/index.js#L75-L123
train
dggriffin/mitto
lib/index.js
_validateConfig
function _validateConfig(configObject, mittoObject) { var packageObject = _findFile('package.json'); if (!mittoObject) { return configObject; } if (!configObject && mittoObject.required && Object.keys(mittoObject.required).length) { throw new Error(mittoObject.name + " configuration file not found, and is required by " + packageObject.name); } else if (!configObject && mittoObject.hasDefault) { return _addOnDefaults({}, mittoObject); } else if (!configObject) { return configObject; } for (var key in mittoObject.required) { if (!configObject.hasOwnProperty(key)) { throw new Error("Required property " + key + " not found in " + mittoObject.name); } else if (_typeof(configObject[key]) !== mittoObject.required[key].type) { throw new Error("Required property " + key + " expected to be of type " + mittoObject.required[key].type); } } for (var key in mittoObject.optional) { if (configObject[key] && _typeof(configObject[key]) !== mittoObject.optional[key].type) { throw new Error("Optional property " + key + " is type " + _typeof(configObject[key]) + " and expected to be of type " + mittoObject.optional[key].type); } } if (mittoObject.hasDefault) { return _addOnDefaults(configObject, mittoObject); } return configObject; }
javascript
function _validateConfig(configObject, mittoObject) { var packageObject = _findFile('package.json'); if (!mittoObject) { return configObject; } if (!configObject && mittoObject.required && Object.keys(mittoObject.required).length) { throw new Error(mittoObject.name + " configuration file not found, and is required by " + packageObject.name); } else if (!configObject && mittoObject.hasDefault) { return _addOnDefaults({}, mittoObject); } else if (!configObject) { return configObject; } for (var key in mittoObject.required) { if (!configObject.hasOwnProperty(key)) { throw new Error("Required property " + key + " not found in " + mittoObject.name); } else if (_typeof(configObject[key]) !== mittoObject.required[key].type) { throw new Error("Required property " + key + " expected to be of type " + mittoObject.required[key].type); } } for (var key in mittoObject.optional) { if (configObject[key] && _typeof(configObject[key]) !== mittoObject.optional[key].type) { throw new Error("Optional property " + key + " is type " + _typeof(configObject[key]) + " and expected to be of type " + mittoObject.optional[key].type); } } if (mittoObject.hasDefault) { return _addOnDefaults(configObject, mittoObject); } return configObject; }
[ "function", "_validateConfig", "(", "configObject", ",", "mittoObject", ")", "{", "var", "packageObject", "=", "_findFile", "(", "'package.json'", ")", ";", "if", "(", "!", "mittoObject", ")", "{", "return", "configObject", ";", "}", "if", "(", "!", "configObject", "&&", "mittoObject", ".", "required", "&&", "Object", ".", "keys", "(", "mittoObject", ".", "required", ")", ".", "length", ")", "{", "throw", "new", "Error", "(", "mittoObject", ".", "name", "+", "\" configuration file not found, and is required by \"", "+", "packageObject", ".", "name", ")", ";", "}", "else", "if", "(", "!", "configObject", "&&", "mittoObject", ".", "hasDefault", ")", "{", "return", "_addOnDefaults", "(", "{", "}", ",", "mittoObject", ")", ";", "}", "else", "if", "(", "!", "configObject", ")", "{", "return", "configObject", ";", "}", "for", "(", "var", "key", "in", "mittoObject", ".", "required", ")", "{", "if", "(", "!", "configObject", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "throw", "new", "Error", "(", "\"Required property \"", "+", "key", "+", "\" not found in \"", "+", "mittoObject", ".", "name", ")", ";", "}", "else", "if", "(", "_typeof", "(", "configObject", "[", "key", "]", ")", "!==", "mittoObject", ".", "required", "[", "key", "]", ".", "type", ")", "{", "throw", "new", "Error", "(", "\"Required property \"", "+", "key", "+", "\" expected to be of type \"", "+", "mittoObject", ".", "required", "[", "key", "]", ".", "type", ")", ";", "}", "}", "for", "(", "var", "key", "in", "mittoObject", ".", "optional", ")", "{", "if", "(", "configObject", "[", "key", "]", "&&", "_typeof", "(", "configObject", "[", "key", "]", ")", "!==", "mittoObject", ".", "optional", "[", "key", "]", ".", "type", ")", "{", "throw", "new", "Error", "(", "\"Optional property \"", "+", "key", "+", "\" is type \"", "+", "_typeof", "(", "configObject", "[", "key", "]", ")", "+", "\" and expected to be of type \"", "+", "mittoObject", ".", "optional", "[", "key", "]", ".", "type", ")", ";", "}", "}", "if", "(", "mittoObject", ".", "hasDefault", ")", "{", "return", "_addOnDefaults", "(", "configObject", ",", "mittoObject", ")", ";", "}", "return", "configObject", ";", "}" ]
Validate the consuming user's present config to ensure it meets the product producer's .mitto syntatical specifications
[ "Validate", "the", "consuming", "user", "s", "present", "config", "to", "ensure", "it", "meets", "the", "product", "producer", "s", ".", "mitto", "syntatical", "specifications" ]
a58cd439b67b626522078b8003a82a348103a66c
https://github.com/dggriffin/mitto/blob/a58cd439b67b626522078b8003a82a348103a66c/lib/index.js#L126-L159
train
yoshuawuyts/urit
index.js
parse
function parse (tmpl) { tmpl = tmpl || '' const parser = uritemplate.parse(tmpl) return function expand (params) { params = params || {} return parser.expand(params) } }
javascript
function parse (tmpl) { tmpl = tmpl || '' const parser = uritemplate.parse(tmpl) return function expand (params) { params = params || {} return parser.expand(params) } }
[ "function", "parse", "(", "tmpl", ")", "{", "tmpl", "=", "tmpl", "||", "''", "const", "parser", "=", "uritemplate", ".", "parse", "(", "tmpl", ")", "return", "function", "expand", "(", "params", ")", "{", "params", "=", "params", "||", "{", "}", "return", "parser", ".", "expand", "(", "params", ")", "}", "}" ]
parse a uri template str -> str
[ "parse", "a", "uri", "template", "str", "-", ">", "str" ]
9f3c9a06a93c509189d9bf9876c5f4d77ee2776e
https://github.com/yoshuawuyts/urit/blob/9f3c9a06a93c509189d9bf9876c5f4d77ee2776e/index.js#L7-L15
train
imlucas/node-stor
stores/localstorage.js
prostrate
function prostrate(source){ return function(method, transform){ transform = transform || {}; return function(){ var args = Array.prototype.slice.call(arguments, 0), fn = args.pop(), res, last; if(args[0] && ['removeItem', 'getItem', 'setItem'].indexOf(method) > -1){ var id = args[0]; id = id.toString(); if(id.indexOf(module.exports.ns) === -1){ id = module.exports.ns + id; } args[0] = id; } if(args.length == 2 && transform.before){ args[1] = transform.before(args[1]); } if(method === 'key'){ assert(typeof args[0] === 'number', args[0] + ' must be a number'); } if(!source[method]){ throw new Error('Unknown localstorage method ' + method); } else{ if(source[method].apply){ res = source[method].apply(source, args); debug('result for ' + method, '(', args, ')', res); } else { res = source[method]; } } try{ if(transform.after){ res = transform.after(res); } } catch(e){} fn(null, res); }; }; }
javascript
function prostrate(source){ return function(method, transform){ transform = transform || {}; return function(){ var args = Array.prototype.slice.call(arguments, 0), fn = args.pop(), res, last; if(args[0] && ['removeItem', 'getItem', 'setItem'].indexOf(method) > -1){ var id = args[0]; id = id.toString(); if(id.indexOf(module.exports.ns) === -1){ id = module.exports.ns + id; } args[0] = id; } if(args.length == 2 && transform.before){ args[1] = transform.before(args[1]); } if(method === 'key'){ assert(typeof args[0] === 'number', args[0] + ' must be a number'); } if(!source[method]){ throw new Error('Unknown localstorage method ' + method); } else{ if(source[method].apply){ res = source[method].apply(source, args); debug('result for ' + method, '(', args, ')', res); } else { res = source[method]; } } try{ if(transform.after){ res = transform.after(res); } } catch(e){} fn(null, res); }; }; }
[ "function", "prostrate", "(", "source", ")", "{", "return", "function", "(", "method", ",", "transform", ")", "{", "transform", "=", "transform", "||", "{", "}", ";", "return", "function", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "0", ")", ",", "fn", "=", "args", ".", "pop", "(", ")", ",", "res", ",", "last", ";", "if", "(", "args", "[", "0", "]", "&&", "[", "'removeItem'", ",", "'getItem'", ",", "'setItem'", "]", ".", "indexOf", "(", "method", ")", ">", "-", "1", ")", "{", "var", "id", "=", "args", "[", "0", "]", ";", "id", "=", "id", ".", "toString", "(", ")", ";", "if", "(", "id", ".", "indexOf", "(", "module", ".", "exports", ".", "ns", ")", "===", "-", "1", ")", "{", "id", "=", "module", ".", "exports", ".", "ns", "+", "id", ";", "}", "args", "[", "0", "]", "=", "id", ";", "}", "if", "(", "args", ".", "length", "==", "2", "&&", "transform", ".", "before", ")", "{", "args", "[", "1", "]", "=", "transform", ".", "before", "(", "args", "[", "1", "]", ")", ";", "}", "if", "(", "method", "===", "'key'", ")", "{", "assert", "(", "typeof", "args", "[", "0", "]", "===", "'number'", ",", "args", "[", "0", "]", "+", "' must be a number'", ")", ";", "}", "if", "(", "!", "source", "[", "method", "]", ")", "{", "throw", "new", "Error", "(", "'Unknown localstorage method '", "+", "method", ")", ";", "}", "else", "{", "if", "(", "source", "[", "method", "]", ".", "apply", ")", "{", "res", "=", "source", "[", "method", "]", ".", "apply", "(", "source", ",", "args", ")", ";", "debug", "(", "'result for '", "+", "method", ",", "'('", ",", "args", ",", "')'", ",", "res", ")", ";", "}", "else", "{", "res", "=", "source", "[", "method", "]", ";", "}", "}", "try", "{", "if", "(", "transform", ".", "after", ")", "{", "res", "=", "transform", ".", "after", "(", "res", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "}", "fn", "(", "null", ",", "res", ")", ";", "}", ";", "}", ";", "}" ]
Make local storage async, get and set JSON-ify.
[ "Make", "local", "storage", "async", "get", "and", "set", "JSON", "-", "ify", "." ]
6b74af52bf160873658bc3570db716d44c33f335
https://github.com/imlucas/node-stor/blob/6b74af52bf160873658bc3570db716d44c33f335/stores/localstorage.js#L5-L50
train
ayecue/node-klass
src/klass/Logger.js
function(args){ return forEach(args,function(_,item){ var messages = this.result, type = typeof item; if (type == 'string') { messages.push('%s'); } else if (type == 'number') { messages.push('%d'); } else if (type == 'boolean') { messages.push('%s'); } else { messages.push('%O'); } },[]); }
javascript
function(args){ return forEach(args,function(_,item){ var messages = this.result, type = typeof item; if (type == 'string') { messages.push('%s'); } else if (type == 'number') { messages.push('%d'); } else if (type == 'boolean') { messages.push('%s'); } else { messages.push('%O'); } },[]); }
[ "function", "(", "args", ")", "{", "return", "forEach", "(", "args", ",", "function", "(", "_", ",", "item", ")", "{", "var", "messages", "=", "this", ".", "result", ",", "type", "=", "typeof", "item", ";", "if", "(", "type", "==", "'string'", ")", "{", "messages", ".", "push", "(", "'%s'", ")", ";", "}", "else", "if", "(", "type", "==", "'number'", ")", "{", "messages", ".", "push", "(", "'%d'", ")", ";", "}", "else", "if", "(", "type", "==", "'boolean'", ")", "{", "messages", ".", "push", "(", "'%s'", ")", ";", "}", "else", "{", "messages", ".", "push", "(", "'%O'", ")", ";", "}", "}", ",", "[", "]", ")", ";", "}" ]
Generating console message templates
[ "Generating", "console", "message", "templates" ]
d0583db943bfc6186e45d205735bebd88828e117
https://github.com/ayecue/node-klass/blob/d0583db943bfc6186e45d205735bebd88828e117/src/klass/Logger.js#L57-L72
train
ayecue/node-klass
src/klass/Logger.js
function(context,args,error,color){ var me = this, base = context.getCalledKlass(), contextName = base ? base.getName() : CONSTANTS.LOGGER.UNKNOWN_NAME, methodName = context.getCalledName() || CONSTANTS.LOGGER.ANONYMOUS_NAME, messages = me.toMessages(args); color = color || (error ? CONSTANTS.LOGGER.EXCEPTION_COLOR : CONSTANTS.LOGGER.SUCCESS_COLOR); if (context) { if (context.deepLoggingLevel || methodName == CONSTANTS.LOGGER.ANONYMOUS_NAME) { var deepTrace = me.analyze(context); console.groupCollapsed.apply(console,[('[node-klass-logger] ' + contextName + '.' + methodName + messages.join(' '))[color]].concat(args)); console.log(('[node-klass-logger] ' + deepTrace)[color]); console.groupEnd(); } else { console.log.apply(console,[('[node-klass-logger] ' + contextName + '.' + methodName + messages.join(' '))[color]].concat(args)); } } else { console.log.apply(console,[('[node-klass-logger]' + messages.join(' '))[color]].concat(args)); } }
javascript
function(context,args,error,color){ var me = this, base = context.getCalledKlass(), contextName = base ? base.getName() : CONSTANTS.LOGGER.UNKNOWN_NAME, methodName = context.getCalledName() || CONSTANTS.LOGGER.ANONYMOUS_NAME, messages = me.toMessages(args); color = color || (error ? CONSTANTS.LOGGER.EXCEPTION_COLOR : CONSTANTS.LOGGER.SUCCESS_COLOR); if (context) { if (context.deepLoggingLevel || methodName == CONSTANTS.LOGGER.ANONYMOUS_NAME) { var deepTrace = me.analyze(context); console.groupCollapsed.apply(console,[('[node-klass-logger] ' + contextName + '.' + methodName + messages.join(' '))[color]].concat(args)); console.log(('[node-klass-logger] ' + deepTrace)[color]); console.groupEnd(); } else { console.log.apply(console,[('[node-klass-logger] ' + contextName + '.' + methodName + messages.join(' '))[color]].concat(args)); } } else { console.log.apply(console,[('[node-klass-logger]' + messages.join(' '))[color]].concat(args)); } }
[ "function", "(", "context", ",", "args", ",", "error", ",", "color", ")", "{", "var", "me", "=", "this", ",", "base", "=", "context", ".", "getCalledKlass", "(", ")", ",", "contextName", "=", "base", "?", "base", ".", "getName", "(", ")", ":", "CONSTANTS", ".", "LOGGER", ".", "UNKNOWN_NAME", ",", "methodName", "=", "context", ".", "getCalledName", "(", ")", "||", "CONSTANTS", ".", "LOGGER", ".", "ANONYMOUS_NAME", ",", "messages", "=", "me", ".", "toMessages", "(", "args", ")", ";", "color", "=", "color", "||", "(", "error", "?", "CONSTANTS", ".", "LOGGER", ".", "EXCEPTION_COLOR", ":", "CONSTANTS", ".", "LOGGER", ".", "SUCCESS_COLOR", ")", ";", "if", "(", "context", ")", "{", "if", "(", "context", ".", "deepLoggingLevel", "||", "methodName", "==", "CONSTANTS", ".", "LOGGER", ".", "ANONYMOUS_NAME", ")", "{", "var", "deepTrace", "=", "me", ".", "analyze", "(", "context", ")", ";", "console", ".", "groupCollapsed", ".", "apply", "(", "console", ",", "[", "(", "'[node-klass-logger] '", "+", "contextName", "+", "'.'", "+", "methodName", "+", "messages", ".", "join", "(", "' '", ")", ")", "[", "color", "]", "]", ".", "concat", "(", "args", ")", ")", ";", "console", ".", "log", "(", "(", "'[node-klass-logger] '", "+", "deepTrace", ")", "[", "color", "]", ")", ";", "console", ".", "groupEnd", "(", ")", ";", "}", "else", "{", "console", ".", "log", ".", "apply", "(", "console", ",", "[", "(", "'[node-klass-logger] '", "+", "contextName", "+", "'.'", "+", "methodName", "+", "messages", ".", "join", "(", "' '", ")", ")", "[", "color", "]", "]", ".", "concat", "(", "args", ")", ")", ";", "}", "}", "else", "{", "console", ".", "log", ".", "apply", "(", "console", ",", "[", "(", "'[node-klass-logger]'", "+", "messages", ".", "join", "(", "' '", ")", ")", "[", "color", "]", "]", ".", "concat", "(", "args", ")", ")", ";", "}", "}" ]
Default print function to show context messages
[ "Default", "print", "function", "to", "show", "context", "messages" ]
d0583db943bfc6186e45d205735bebd88828e117
https://github.com/ayecue/node-klass/blob/d0583db943bfc6186e45d205735bebd88828e117/src/klass/Logger.js#L77-L99
train
taf2/tiamat
lib/tiamat/server.js
resetWorker
function resetWorker() { sigqueue = []; mastersigs.forEach(process.removeAllListeners.bind(process)); process.removeAllListeners('exit'); process.env.TIAMAT = '1'; }
javascript
function resetWorker() { sigqueue = []; mastersigs.forEach(process.removeAllListeners.bind(process)); process.removeAllListeners('exit'); process.env.TIAMAT = '1'; }
[ "function", "resetWorker", "(", ")", "{", "sigqueue", "=", "[", "]", ";", "mastersigs", ".", "forEach", "(", "process", ".", "removeAllListeners", ".", "bind", "(", "process", ")", ")", ";", "process", ".", "removeAllListeners", "(", "'exit'", ")", ";", "process", ".", "env", ".", "TIAMAT", "=", "'1'", ";", "}" ]
unregister events setup by master
[ "unregister", "events", "setup", "by", "master" ]
f51a33bb94897bc5c9e1849990b418d0bfe49e48
https://github.com/taf2/tiamat/blob/f51a33bb94897bc5c9e1849990b418d0bfe49e48/lib/tiamat/server.js#L227-L232
train
chrisenytc/gngb-api
lib/gngb-api.js
function (res, name, version) { //Options var imgPath, width; //RegExp var re = /^\d\.\d.\d$/; //Test version if (re.test(version)) { imgPath = path.join(dir, name + '.png'); width = 76; } else if (version.length === 6) { imgPath = path.join(dir, name + '-larger.png'); width = 80; } else if (version.length === 7) { imgPath = path.join(dir, name + '-larger.png'); width = 77; } else { imgPath = path.join(dir, name + '-larger.png'); width = 74; } //Create Image var base = gm(imgPath) .font(path.join(__dirname, 'fonts', 'Arial.ttf')) .fontSize(10) .fill('#ffffff') .drawText(width, 12, version); //Write Stream and send to client write(base, res); }
javascript
function (res, name, version) { //Options var imgPath, width; //RegExp var re = /^\d\.\d.\d$/; //Test version if (re.test(version)) { imgPath = path.join(dir, name + '.png'); width = 76; } else if (version.length === 6) { imgPath = path.join(dir, name + '-larger.png'); width = 80; } else if (version.length === 7) { imgPath = path.join(dir, name + '-larger.png'); width = 77; } else { imgPath = path.join(dir, name + '-larger.png'); width = 74; } //Create Image var base = gm(imgPath) .font(path.join(__dirname, 'fonts', 'Arial.ttf')) .fontSize(10) .fill('#ffffff') .drawText(width, 12, version); //Write Stream and send to client write(base, res); }
[ "function", "(", "res", ",", "name", ",", "version", ")", "{", "var", "imgPath", ",", "width", ";", "var", "re", "=", "/", "^\\d\\.\\d.\\d$", "/", ";", "if", "(", "re", ".", "test", "(", "version", ")", ")", "{", "imgPath", "=", "path", ".", "join", "(", "dir", ",", "name", "+", "'.png'", ")", ";", "width", "=", "76", ";", "}", "else", "if", "(", "version", ".", "length", "===", "6", ")", "{", "imgPath", "=", "path", ".", "join", "(", "dir", ",", "name", "+", "'-larger.png'", ")", ";", "width", "=", "80", ";", "}", "else", "if", "(", "version", ".", "length", "===", "7", ")", "{", "imgPath", "=", "path", ".", "join", "(", "dir", ",", "name", "+", "'-larger.png'", ")", ";", "width", "=", "77", ";", "}", "else", "{", "imgPath", "=", "path", ".", "join", "(", "dir", ",", "name", "+", "'-larger.png'", ")", ";", "width", "=", "74", ";", "}", "var", "base", "=", "gm", "(", "imgPath", ")", ".", "font", "(", "path", ".", "join", "(", "__dirname", ",", "'fonts'", ",", "'Arial.ttf'", ")", ")", ".", "fontSize", "(", "10", ")", ".", "fill", "(", "'#ffffff'", ")", ".", "drawText", "(", "width", ",", "12", ",", "version", ")", ";", "write", "(", "base", ",", "res", ")", ";", "}" ]
Create version badge
[ "Create", "version", "badge" ]
020e8c9cb899fb3df0da452151d7afb5e6be78f5
https://github.com/chrisenytc/gngb-api/blob/020e8c9cb899fb3df0da452151d7afb5e6be78f5/lib/gngb-api.js#L43-L71
train
chrisenytc/gngb-api
lib/gngb-api.js
function (service, name, user) { // var services = []; // services['gh'] = 'https://api.github.com/repos/:user/:name/releases'; services['npm'] = 'http://registry.npmjs.org/:name/latest'; services['gem'] = 'https://rubygems.org/api/v1/gems/:name.json'; services['bower'] = 'https://api.github.com/repos/:user/:name/releases'; var str = services[service].replace(':name', name).replace(':user', user); // return str; }
javascript
function (service, name, user) { // var services = []; // services['gh'] = 'https://api.github.com/repos/:user/:name/releases'; services['npm'] = 'http://registry.npmjs.org/:name/latest'; services['gem'] = 'https://rubygems.org/api/v1/gems/:name.json'; services['bower'] = 'https://api.github.com/repos/:user/:name/releases'; var str = services[service].replace(':name', name).replace(':user', user); // return str; }
[ "function", "(", "service", ",", "name", ",", "user", ")", "{", "var", "services", "=", "[", "]", ";", "services", "[", "'gh'", "]", "=", "'https://api.github.com/repos/:user/:name/releases'", ";", "services", "[", "'npm'", "]", "=", "'http://registry.npmjs.org/:name/latest'", ";", "services", "[", "'gem'", "]", "=", "'https://rubygems.org/api/v1/gems/:name.json'", ";", "services", "[", "'bower'", "]", "=", "'https://api.github.com/repos/:user/:name/releases'", ";", "var", "str", "=", "services", "[", "service", "]", ".", "replace", "(", "':name'", ",", "name", ")", ".", "replace", "(", "':user'", ",", "user", ")", ";", "return", "str", ";", "}" ]
Get formated service url
[ "Get", "formated", "service", "url" ]
020e8c9cb899fb3df0da452151d7afb5e6be78f5
https://github.com/chrisenytc/gngb-api/blob/020e8c9cb899fb3df0da452151d7afb5e6be78f5/lib/gngb-api.js#L74-L87
train
chrisenytc/gngb-api
lib/gngb-api.js
function (service, data) { switch (service) { case 'gh': return data[0].tag_name.replace(/^v/, ''); case 'npm': return data.version; case 'gem': return data.version; case 'bower': return data[0].tag_name.replace(/^v/, ''); default: console.log(service + 'not found!'); break; } }
javascript
function (service, data) { switch (service) { case 'gh': return data[0].tag_name.replace(/^v/, ''); case 'npm': return data.version; case 'gem': return data.version; case 'bower': return data[0].tag_name.replace(/^v/, ''); default: console.log(service + 'not found!'); break; } }
[ "function", "(", "service", ",", "data", ")", "{", "switch", "(", "service", ")", "{", "case", "'gh'", ":", "return", "data", "[", "0", "]", ".", "tag_name", ".", "replace", "(", "/", "^v", "/", ",", "''", ")", ";", "case", "'npm'", ":", "return", "data", ".", "version", ";", "case", "'gem'", ":", "return", "data", ".", "version", ";", "case", "'bower'", ":", "return", "data", "[", "0", "]", ".", "tag_name", ".", "replace", "(", "/", "^v", "/", ",", "''", ")", ";", "default", ":", "console", ".", "log", "(", "service", "+", "'not found!'", ")", ";", "break", ";", "}", "}" ]
Get data and format version
[ "Get", "data", "and", "format", "version" ]
020e8c9cb899fb3df0da452151d7afb5e6be78f5
https://github.com/chrisenytc/gngb-api/blob/020e8c9cb899fb3df0da452151d7afb5e6be78f5/lib/gngb-api.js#L90-L104
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/resourcemanager.js
function( names, callback, scope ) { // Ensure that we have an array of names. if ( !CKEDITOR.tools.isArray( names ) ) names = names ? [ names ] : []; var loaded = this.loaded, registered = this.registered, urls = [], urlsNames = {}, resources = {}; // Loop through all names. for ( var i = 0; i < names.length; i++ ) { var name = names[ i ]; if ( !name ) continue; // If not available yet. if ( !loaded[ name ] && !registered[ name ] ) { var url = this.getFilePath( name ); urls.push( url ); if ( !( url in urlsNames ) ) urlsNames[ url ] = []; urlsNames[ url ].push( name ); } else { resources[ name ] = this.get( name ); } } CKEDITOR.scriptLoader.load( urls, function( completed, failed ) { if ( failed.length ) { throw '[CKEDITOR.resourceManager.load] Resource name "' + urlsNames[ failed[ 0 ] ].join( ',' ) + '" was not found at "' + failed[ 0 ] + '".'; } for ( var i = 0; i < completed.length; i++ ) { var nameList = urlsNames[ completed[ i ] ]; for ( var j = 0; j < nameList.length; j++ ) { var name = nameList[ j ]; resources[ name ] = this.get( name ); loaded[ name ] = 1; } } callback.call( scope, resources ); }, this ); }
javascript
function( names, callback, scope ) { // Ensure that we have an array of names. if ( !CKEDITOR.tools.isArray( names ) ) names = names ? [ names ] : []; var loaded = this.loaded, registered = this.registered, urls = [], urlsNames = {}, resources = {}; // Loop through all names. for ( var i = 0; i < names.length; i++ ) { var name = names[ i ]; if ( !name ) continue; // If not available yet. if ( !loaded[ name ] && !registered[ name ] ) { var url = this.getFilePath( name ); urls.push( url ); if ( !( url in urlsNames ) ) urlsNames[ url ] = []; urlsNames[ url ].push( name ); } else { resources[ name ] = this.get( name ); } } CKEDITOR.scriptLoader.load( urls, function( completed, failed ) { if ( failed.length ) { throw '[CKEDITOR.resourceManager.load] Resource name "' + urlsNames[ failed[ 0 ] ].join( ',' ) + '" was not found at "' + failed[ 0 ] + '".'; } for ( var i = 0; i < completed.length; i++ ) { var nameList = urlsNames[ completed[ i ] ]; for ( var j = 0; j < nameList.length; j++ ) { var name = nameList[ j ]; resources[ name ] = this.get( name ); loaded[ name ] = 1; } } callback.call( scope, resources ); }, this ); }
[ "function", "(", "names", ",", "callback", ",", "scope", ")", "{", "if", "(", "!", "CKEDITOR", ".", "tools", ".", "isArray", "(", "names", ")", ")", "names", "=", "names", "?", "[", "names", "]", ":", "[", "]", ";", "var", "loaded", "=", "this", ".", "loaded", ",", "registered", "=", "this", ".", "registered", ",", "urls", "=", "[", "]", ",", "urlsNames", "=", "{", "}", ",", "resources", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "names", ".", "length", ";", "i", "++", ")", "{", "var", "name", "=", "names", "[", "i", "]", ";", "if", "(", "!", "name", ")", "continue", ";", "if", "(", "!", "loaded", "[", "name", "]", "&&", "!", "registered", "[", "name", "]", ")", "{", "var", "url", "=", "this", ".", "getFilePath", "(", "name", ")", ";", "urls", ".", "push", "(", "url", ")", ";", "if", "(", "!", "(", "url", "in", "urlsNames", ")", ")", "urlsNames", "[", "url", "]", "=", "[", "]", ";", "urlsNames", "[", "url", "]", ".", "push", "(", "name", ")", ";", "}", "else", "{", "resources", "[", "name", "]", "=", "this", ".", "get", "(", "name", ")", ";", "}", "}", "CKEDITOR", ".", "scriptLoader", ".", "load", "(", "urls", ",", "function", "(", "completed", ",", "failed", ")", "{", "if", "(", "failed", ".", "length", ")", "{", "throw", "'[CKEDITOR.resourceManager.load] Resource name \"'", "+", "urlsNames", "[", "failed", "[", "0", "]", "]", ".", "join", "(", "','", ")", "+", "'\" was not found at \"'", "+", "failed", "[", "0", "]", "+", "'\".'", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "completed", ".", "length", ";", "i", "++", ")", "{", "var", "nameList", "=", "urlsNames", "[", "completed", "[", "i", "]", "]", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "nameList", ".", "length", ";", "j", "++", ")", "{", "var", "name", "=", "nameList", "[", "j", "]", ";", "resources", "[", "name", "]", "=", "this", ".", "get", "(", "name", ")", ";", "loaded", "[", "name", "]", "=", "1", ";", "}", "}", "callback", ".", "call", "(", "scope", ",", "resources", ")", ";", "}", ",", "this", ")", ";", "}" ]
Loads one or more resources. CKEDITOR.plugins.load( 'myplugin', function( plugins ) { alert( plugins[ 'myplugin' ] ); // object } ); @param {String/Array} name The name of the resource to load. It may be a string with a single resource name, or an array with several names. @param {Function} callback A function to be called when all resources are loaded. The callback will receive an array containing all loaded names. @param {Object} [scope] The scope object to be used for the callback call.
[ "Loads", "one", "or", "more", "resources", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/resourcemanager.js#L179-L227
train
bengreenier/lconf
Parser.js
load
function load(file) { if (path.extname(file) === ".yaml" || path.extname(file) === ".yml") { return yaml.safeLoad(fs.readFileSync(file)); } else if (path.extname(file) === ".json") { var r = JSON.parse(fs.readFileSync(file)); return r; } else if (path.extname(file) === ".js") { var obj = require(file); if (typeof(obj) !== "object") { throw {error: "needs to export object, not "+typeof(obj), file: file}; } else { return clone(obj); } } else { throw {error: path+" has invalid extension: "+path.extname(file)}; } }
javascript
function load(file) { if (path.extname(file) === ".yaml" || path.extname(file) === ".yml") { return yaml.safeLoad(fs.readFileSync(file)); } else if (path.extname(file) === ".json") { var r = JSON.parse(fs.readFileSync(file)); return r; } else if (path.extname(file) === ".js") { var obj = require(file); if (typeof(obj) !== "object") { throw {error: "needs to export object, not "+typeof(obj), file: file}; } else { return clone(obj); } } else { throw {error: path+" has invalid extension: "+path.extname(file)}; } }
[ "function", "load", "(", "file", ")", "{", "if", "(", "path", ".", "extname", "(", "file", ")", "===", "\".yaml\"", "||", "path", ".", "extname", "(", "file", ")", "===", "\".yml\"", ")", "{", "return", "yaml", ".", "safeLoad", "(", "fs", ".", "readFileSync", "(", "file", ")", ")", ";", "}", "else", "if", "(", "path", ".", "extname", "(", "file", ")", "===", "\".json\"", ")", "{", "var", "r", "=", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "file", ")", ")", ";", "return", "r", ";", "}", "else", "if", "(", "path", ".", "extname", "(", "file", ")", "===", "\".js\"", ")", "{", "var", "obj", "=", "require", "(", "file", ")", ";", "if", "(", "typeof", "(", "obj", ")", "!==", "\"object\"", ")", "{", "throw", "{", "error", ":", "\"needs to export object, not \"", "+", "typeof", "(", "obj", ")", ",", "file", ":", "file", "}", ";", "}", "else", "{", "return", "clone", "(", "obj", ")", ";", "}", "}", "else", "{", "throw", "{", "error", ":", "path", "+", "\" has invalid extension: \"", "+", "path", ".", "extname", "(", "file", ")", "}", ";", "}", "}" ]
Does the actual file parsing
[ "Does", "the", "actual", "file", "parsing" ]
212b7e15dc18585be99600a505b35fe94f9758ea
https://github.com/bengreenier/lconf/blob/212b7e15dc18585be99600a505b35fe94f9758ea/Parser.js#L59-L79
train
bjnortier/triptych
build/events/EventGenerator.js
addOffset
function addOffset(element, event) { event.offsetX = Math.round(event.pageX - element.offset().left); event.offsetY = Math.round(event.pageY - element.offset().top); return event; }
javascript
function addOffset(element, event) { event.offsetX = Math.round(event.pageX - element.offset().left); event.offsetY = Math.round(event.pageY - element.offset().top); return event; }
[ "function", "addOffset", "(", "element", ",", "event", ")", "{", "event", ".", "offsetX", "=", "Math", ".", "round", "(", "event", ".", "pageX", "-", "element", ".", "offset", "(", ")", ".", "left", ")", ";", "event", ".", "offsetY", "=", "Math", ".", "round", "(", "event", ".", "pageY", "-", "element", ".", "offset", "(", ")", ".", "top", ")", ";", "return", "event", ";", "}" ]
Add offset support to all browsers
[ "Add", "offset", "support", "to", "all", "browsers" ]
3f61ac1b74842ac48d8a1eaef9e71becbcfb1e8a
https://github.com/bjnortier/triptych/blob/3f61ac1b74842ac48d8a1eaef9e71becbcfb1e8a/build/events/EventGenerator.js#L9-L13
train
oskarhagberg/gbgcity
lib/traveltime.js
getRoute
function getRoute(id, params, callback) { params = params || {}; core.callApiWithPathSegment('/TravelTimesService/v1.0/Routes', id, params, callback); }
javascript
function getRoute(id, params, callback) { params = params || {}; core.callApiWithPathSegment('/TravelTimesService/v1.0/Routes', id, params, callback); }
[ "function", "getRoute", "(", "id", ",", "params", ",", "callback", ")", "{", "params", "=", "params", "||", "{", "}", ";", "core", ".", "callApiWithPathSegment", "(", "'/TravelTimesService/v1.0/Routes'", ",", "id", ",", "params", ",", "callback", ")", ";", "}" ]
Returns a route @memberof module:gbgcity/TravelTime @param {String} id The id of the route @param {Object} [params] An object containing additional parameters. @param {Function} callback The function to call with results, function({Error} error, {Object} results)/ @see http://data.goteborg.se/TravelTimesService/v1.0/help/operations/GetRoute
[ "Returns", "a", "route" ]
d2de903b2fba83cc953ae218905380fef080cb2d
https://github.com/oskarhagberg/gbgcity/blob/d2de903b2fba83cc953ae218905380fef080cb2d/lib/traveltime.js#L27-L30
train
scazan/taskengine
taskengine.js
readTasks
function readTasks(err, data, callback) { this.tasks = JSON.parse(data); var sortedTasks = _.sortBy(this.tasks, function(task) { return parseInt(task.id, 10); }); largestID = sortedTasks[sortedTasks.length-1].id; if(callback) { callback(err, this); } }
javascript
function readTasks(err, data, callback) { this.tasks = JSON.parse(data); var sortedTasks = _.sortBy(this.tasks, function(task) { return parseInt(task.id, 10); }); largestID = sortedTasks[sortedTasks.length-1].id; if(callback) { callback(err, this); } }
[ "function", "readTasks", "(", "err", ",", "data", ",", "callback", ")", "{", "this", ".", "tasks", "=", "JSON", ".", "parse", "(", "data", ")", ";", "var", "sortedTasks", "=", "_", ".", "sortBy", "(", "this", ".", "tasks", ",", "function", "(", "task", ")", "{", "return", "parseInt", "(", "task", ".", "id", ",", "10", ")", ";", "}", ")", ";", "largestID", "=", "sortedTasks", "[", "sortedTasks", ".", "length", "-", "1", "]", ".", "id", ";", "if", "(", "callback", ")", "{", "callback", "(", "err", ",", "this", ")", ";", "}", "}" ]
Parse the tasks from a string and set the global tasks array @param err @param {String} data @param {function} callback @return {undefined}
[ "Parse", "the", "tasks", "from", "a", "string", "and", "set", "the", "global", "tasks", "array" ]
0fa7d67f8d33f03fdc10174561110660963a52db
https://github.com/scazan/taskengine/blob/0fa7d67f8d33f03fdc10174561110660963a52db/taskengine.js#L56-L65
train
scazan/taskengine
taskengine.js
addTask
function addTask(taskData, subTaskData) { var subTaskList, parsedData, subTask = false; if(taskData !== undefined) { if(parseInt(taskData,10) > -1) { subTaskList = this.getTaskByID(parseInt(taskData,10)).subTasks; parsedData = this.parseInputData(subTaskData); subTask = true; } else { parsedData = this.parseInputData(taskData); } var newTask = _.clone(defaultTask) _.extend(newTask, parsedData); newTask.dateAdded = Date.now(); newTask.id = largestID + 1; newTask.subTask = subTask; this.tasks.unshift( newTask ); if(subTask) { subTaskList.push(newTask.id); } console.log('Added:'); return newTask; } else { console.log('no task name given'); return false; } }
javascript
function addTask(taskData, subTaskData) { var subTaskList, parsedData, subTask = false; if(taskData !== undefined) { if(parseInt(taskData,10) > -1) { subTaskList = this.getTaskByID(parseInt(taskData,10)).subTasks; parsedData = this.parseInputData(subTaskData); subTask = true; } else { parsedData = this.parseInputData(taskData); } var newTask = _.clone(defaultTask) _.extend(newTask, parsedData); newTask.dateAdded = Date.now(); newTask.id = largestID + 1; newTask.subTask = subTask; this.tasks.unshift( newTask ); if(subTask) { subTaskList.push(newTask.id); } console.log('Added:'); return newTask; } else { console.log('no task name given'); return false; } }
[ "function", "addTask", "(", "taskData", ",", "subTaskData", ")", "{", "var", "subTaskList", ",", "parsedData", ",", "subTask", "=", "false", ";", "if", "(", "taskData", "!==", "undefined", ")", "{", "if", "(", "parseInt", "(", "taskData", ",", "10", ")", ">", "-", "1", ")", "{", "subTaskList", "=", "this", ".", "getTaskByID", "(", "parseInt", "(", "taskData", ",", "10", ")", ")", ".", "subTasks", ";", "parsedData", "=", "this", ".", "parseInputData", "(", "subTaskData", ")", ";", "subTask", "=", "true", ";", "}", "else", "{", "parsedData", "=", "this", ".", "parseInputData", "(", "taskData", ")", ";", "}", "var", "newTask", "=", "_", ".", "clone", "(", "defaultTask", ")", "_", ".", "extend", "(", "newTask", ",", "parsedData", ")", ";", "newTask", ".", "dateAdded", "=", "Date", ".", "now", "(", ")", ";", "newTask", ".", "id", "=", "largestID", "+", "1", ";", "newTask", ".", "subTask", "=", "subTask", ";", "this", ".", "tasks", ".", "unshift", "(", "newTask", ")", ";", "if", "(", "subTask", ")", "{", "subTaskList", ".", "push", "(", "newTask", ".", "id", ")", ";", "}", "console", ".", "log", "(", "'Added:'", ")", ";", "return", "newTask", ";", "}", "else", "{", "console", ".", "log", "(", "'no task name given'", ")", ";", "return", "false", ";", "}", "}" ]
Add the given task to our array @param taskData @param callback @return {undefined}
[ "Add", "the", "given", "task", "to", "our", "array" ]
0fa7d67f8d33f03fdc10174561110660963a52db
https://github.com/scazan/taskengine/blob/0fa7d67f8d33f03fdc10174561110660963a52db/taskengine.js#L124-L162
train
scazan/taskengine
taskengine.js
closeTask
function closeTask(taskID) { taskID = parseInt(taskID, 10); var task = this.getTaskByID(taskID); if(task) { task.open = false; console.log('closing:'); return task; } else { return false; } }
javascript
function closeTask(taskID) { taskID = parseInt(taskID, 10); var task = this.getTaskByID(taskID); if(task) { task.open = false; console.log('closing:'); return task; } else { return false; } }
[ "function", "closeTask", "(", "taskID", ")", "{", "taskID", "=", "parseInt", "(", "taskID", ",", "10", ")", ";", "var", "task", "=", "this", ".", "getTaskByID", "(", "taskID", ")", ";", "if", "(", "task", ")", "{", "task", ".", "open", "=", "false", ";", "console", ".", "log", "(", "'closing:'", ")", ";", "return", "task", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Set a task as "done" or "closed" @return {undefined}
[ "Set", "a", "task", "as", "done", "or", "closed" ]
0fa7d67f8d33f03fdc10174561110660963a52db
https://github.com/scazan/taskengine/blob/0fa7d67f8d33f03fdc10174561110660963a52db/taskengine.js#L214-L228
train
sigmaframeworks/sigma-libs
src/phonelib.js
getExample
function getExample(countryCode, numberType, national) { try { var phoneUtil = i18n.phonenumbers.PhoneNumberUtil.getInstance(); var numberObj = phoneUtil.getExampleNumberForType(countryCode, numberType); var format = (national) ? i18n.phonenumbers.PhoneNumberFormat.NATIONAL : i18n.phonenumbers.PhoneNumberFormat.INTERNATIONAL; return phoneUtil.format(numberObj, format); } catch (e) { return ""; } }
javascript
function getExample(countryCode, numberType, national) { try { var phoneUtil = i18n.phonenumbers.PhoneNumberUtil.getInstance(); var numberObj = phoneUtil.getExampleNumberForType(countryCode, numberType); var format = (national) ? i18n.phonenumbers.PhoneNumberFormat.NATIONAL : i18n.phonenumbers.PhoneNumberFormat.INTERNATIONAL; return phoneUtil.format(numberObj, format); } catch (e) { return ""; } }
[ "function", "getExample", "(", "countryCode", ",", "numberType", ",", "national", ")", "{", "try", "{", "var", "phoneUtil", "=", "i18n", ".", "phonenumbers", ".", "PhoneNumberUtil", ".", "getInstance", "(", ")", ";", "var", "numberObj", "=", "phoneUtil", ".", "getExampleNumberForType", "(", "countryCode", ",", "numberType", ")", ";", "var", "format", "=", "(", "national", ")", "?", "i18n", ".", "phonenumbers", ".", "PhoneNumberFormat", ".", "NATIONAL", ":", "i18n", ".", "phonenumbers", ".", "PhoneNumberFormat", ".", "INTERNATIONAL", ";", "return", "phoneUtil", ".", "format", "(", "numberObj", ",", "format", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "\"\"", ";", "}", "}" ]
get an example number for the given country code
[ "get", "an", "example", "number", "for", "the", "given", "country", "code" ]
a2a835bad8f9e08d32a9d4541a14b13a3fed4055
https://github.com/sigmaframeworks/sigma-libs/blob/a2a835bad8f9e08d32a9d4541a14b13a3fed4055/src/phonelib.js#L18-L27
train
sigmaframeworks/sigma-libs
src/phonelib.js
format
function format(number, countryCode, type) { try { var phoneUtil = i18n.phonenumbers.PhoneNumberUtil.getInstance(); var numberObj = phoneUtil.parseAndKeepRawInput(number, countryCode || ''); type = (typeof type == "undefined") ? i18n.phonenumbers.PhoneNumberFormat.INTERNATIONAL : type; if (type == 0) { return phoneUtil.format(numberObj, i18n.phonenumbers.PhoneNumberFormat.INTERNATIONAL).replace(/[\-\(\)\s\.]/g, '').replace('ext', ','); } return phoneUtil.format(numberObj, type); } catch (e) { return ""; } }
javascript
function format(number, countryCode, type) { try { var phoneUtil = i18n.phonenumbers.PhoneNumberUtil.getInstance(); var numberObj = phoneUtil.parseAndKeepRawInput(number, countryCode || ''); type = (typeof type == "undefined") ? i18n.phonenumbers.PhoneNumberFormat.INTERNATIONAL : type; if (type == 0) { return phoneUtil.format(numberObj, i18n.phonenumbers.PhoneNumberFormat.INTERNATIONAL).replace(/[\-\(\)\s\.]/g, '').replace('ext', ','); } return phoneUtil.format(numberObj, type); } catch (e) { return ""; } }
[ "function", "format", "(", "number", ",", "countryCode", ",", "type", ")", "{", "try", "{", "var", "phoneUtil", "=", "i18n", ".", "phonenumbers", ".", "PhoneNumberUtil", ".", "getInstance", "(", ")", ";", "var", "numberObj", "=", "phoneUtil", ".", "parseAndKeepRawInput", "(", "number", ",", "countryCode", "||", "''", ")", ";", "type", "=", "(", "typeof", "type", "==", "\"undefined\"", ")", "?", "i18n", ".", "phonenumbers", ".", "PhoneNumberFormat", ".", "INTERNATIONAL", ":", "type", ";", "if", "(", "type", "==", "0", ")", "{", "return", "phoneUtil", ".", "format", "(", "numberObj", ",", "i18n", ".", "phonenumbers", ".", "PhoneNumberFormat", ".", "INTERNATIONAL", ")", ".", "replace", "(", "/", "[\\-\\(\\)\\s\\.]", "/", "g", ",", "''", ")", ".", "replace", "(", "'ext'", ",", "','", ")", ";", "}", "return", "phoneUtil", ".", "format", "(", "numberObj", ",", "type", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "\"\"", ";", "}", "}" ]
format the given number to the given type
[ "format", "the", "given", "number", "to", "the", "given", "type" ]
a2a835bad8f9e08d32a9d4541a14b13a3fed4055
https://github.com/sigmaframeworks/sigma-libs/blob/a2a835bad8f9e08d32a9d4541a14b13a3fed4055/src/phonelib.js#L31-L43
train
sigmaframeworks/sigma-libs
src/phonelib.js
isValid
function isValid(number, countryCode) { try { var phoneUtil = i18n.phonenumbers.PhoneNumberUtil.getInstance(); var numberObj = phoneUtil.parseAndKeepRawInput(number, countryCode); return phoneUtil.isValidNumber(numberObj); } catch (e) { return false; } }
javascript
function isValid(number, countryCode) { try { var phoneUtil = i18n.phonenumbers.PhoneNumberUtil.getInstance(); var numberObj = phoneUtil.parseAndKeepRawInput(number, countryCode); return phoneUtil.isValidNumber(numberObj); } catch (e) { return false; } }
[ "function", "isValid", "(", "number", ",", "countryCode", ")", "{", "try", "{", "var", "phoneUtil", "=", "i18n", ".", "phonenumbers", ".", "PhoneNumberUtil", ".", "getInstance", "(", ")", ";", "var", "numberObj", "=", "phoneUtil", ".", "parseAndKeepRawInput", "(", "number", ",", "countryCode", ")", ";", "return", "phoneUtil", ".", "isValidNumber", "(", "numberObj", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "false", ";", "}", "}" ]
check if given number is valid
[ "check", "if", "given", "number", "is", "valid" ]
a2a835bad8f9e08d32a9d4541a14b13a3fed4055
https://github.com/sigmaframeworks/sigma-libs/blob/a2a835bad8f9e08d32a9d4541a14b13a3fed4055/src/phonelib.js#L109-L117
train
raincatcher-beta/raincatcher-file-angular
lib/file-client/index.js
create
function create(fileToCreate) { //Creating a unique channel to get the response var topicUid = shortid.generate(); var topicParams = {topicUid: topicUid, itemToCreate: fileToCreate}; var donePromise = mediator.promise(fileSubscribers.getTopic(CONSTANTS.TOPICS.CREATE, CONSTANTS.DONE_PREFIX, topicUid)); var errorPromise = mediator.promise(fileSubscribers.getTopic(CONSTANTS.TOPICS.CREATE, CONSTANTS.ERROR_PREFIX, topicUid)); mediator.publish(fileSubscribers.getTopic(CONSTANTS.TOPICS.CREATE), topicParams); return getTopicPromises(donePromise, errorPromise); }
javascript
function create(fileToCreate) { //Creating a unique channel to get the response var topicUid = shortid.generate(); var topicParams = {topicUid: topicUid, itemToCreate: fileToCreate}; var donePromise = mediator.promise(fileSubscribers.getTopic(CONSTANTS.TOPICS.CREATE, CONSTANTS.DONE_PREFIX, topicUid)); var errorPromise = mediator.promise(fileSubscribers.getTopic(CONSTANTS.TOPICS.CREATE, CONSTANTS.ERROR_PREFIX, topicUid)); mediator.publish(fileSubscribers.getTopic(CONSTANTS.TOPICS.CREATE), topicParams); return getTopicPromises(donePromise, errorPromise); }
[ "function", "create", "(", "fileToCreate", ")", "{", "var", "topicUid", "=", "shortid", ".", "generate", "(", ")", ";", "var", "topicParams", "=", "{", "topicUid", ":", "topicUid", ",", "itemToCreate", ":", "fileToCreate", "}", ";", "var", "donePromise", "=", "mediator", ".", "promise", "(", "fileSubscribers", ".", "getTopic", "(", "CONSTANTS", ".", "TOPICS", ".", "CREATE", ",", "CONSTANTS", ".", "DONE_PREFIX", ",", "topicUid", ")", ")", ";", "var", "errorPromise", "=", "mediator", ".", "promise", "(", "fileSubscribers", ".", "getTopic", "(", "CONSTANTS", ".", "TOPICS", ".", "CREATE", ",", "CONSTANTS", ".", "ERROR_PREFIX", ",", "topicUid", ")", ")", ";", "mediator", ".", "publish", "(", "fileSubscribers", ".", "getTopic", "(", "CONSTANTS", ".", "TOPICS", ".", "CREATE", ")", ",", "topicParams", ")", ";", "return", "getTopicPromises", "(", "donePromise", ",", "errorPromise", ")", ";", "}" ]
Creating a new file. @param {object} fileToCreate - The File to create.
[ "Creating", "a", "new", "file", "." ]
a76d406ca62d6c29da3caf94cc9db75f343ec797
https://github.com/raincatcher-beta/raincatcher-file-angular/blob/a76d406ca62d6c29da3caf94cc9db75f343ec797/lib/file-client/index.js#L40-L49
train
raincatcher-beta/raincatcher-file-angular
lib/file-client/index.js
list
function list() { var donePromise = mediator.promise(fileSubscribers.getTopic(CONSTANTS.TOPICS.LIST, CONSTANTS.DONE_PREFIX)); var errorPromise = mediator.promise(fileSubscribers.getTopic(CONSTANTS.TOPICS.LIST, CONSTANTS.ERROR_PREFIX)); mediator.publish(fileSubscribers.getTopic(CONSTANTS.TOPICS.LIST)); return getTopicPromises(donePromise, errorPromise); }
javascript
function list() { var donePromise = mediator.promise(fileSubscribers.getTopic(CONSTANTS.TOPICS.LIST, CONSTANTS.DONE_PREFIX)); var errorPromise = mediator.promise(fileSubscribers.getTopic(CONSTANTS.TOPICS.LIST, CONSTANTS.ERROR_PREFIX)); mediator.publish(fileSubscribers.getTopic(CONSTANTS.TOPICS.LIST)); return getTopicPromises(donePromise, errorPromise); }
[ "function", "list", "(", ")", "{", "var", "donePromise", "=", "mediator", ".", "promise", "(", "fileSubscribers", ".", "getTopic", "(", "CONSTANTS", ".", "TOPICS", ".", "LIST", ",", "CONSTANTS", ".", "DONE_PREFIX", ")", ")", ";", "var", "errorPromise", "=", "mediator", ".", "promise", "(", "fileSubscribers", ".", "getTopic", "(", "CONSTANTS", ".", "TOPICS", ".", "LIST", ",", "CONSTANTS", ".", "ERROR_PREFIX", ")", ")", ";", "mediator", ".", "publish", "(", "fileSubscribers", ".", "getTopic", "(", "CONSTANTS", ".", "TOPICS", ".", "LIST", ")", ")", ";", "return", "getTopicPromises", "(", "donePromise", ",", "errorPromise", ")", ";", "}" ]
Listing All Files
[ "Listing", "All", "Files" ]
a76d406ca62d6c29da3caf94cc9db75f343ec797
https://github.com/raincatcher-beta/raincatcher-file-angular/blob/a76d406ca62d6c29da3caf94cc9db75f343ec797/lib/file-client/index.js#L54-L60
train
thomasmodeneis/soundcloudnodejs
soundcloudnodejs.js
addTrack
function addTrack(options) { return new Promise(function (resolve, reject) { var form = new FormData(); form.append('format', 'json'); if (!options.title) { reject('Error while addTrack track options.title is required but is null'); } else { form.append('track[title]', options.title); } if (!options.description) { reject('Error while addTrack track options.description is required but is null'); } else { form.append('track[description]', options.description); } if (!options.genre) { reject('Error while addTrack track options.genre is required but is null'); } else { form.append('track[genre]', options.genre); } var exist_artwork_data = fs.existsSync(options.artwork_data); if (exist_artwork_data) { form.append('track[artwork_data]', fs.createReadStream(options.artwork_data)); } if (options.tag_list) { form.append('track[tag_list]', options.tag_list); } form.append('track[sharing]', options.sharing); if (!options.oauth_token) { reject('Error while addTrack track oauth_token is required but is null'); } else { form.append('oauth_token', options.oauth_token); } if (!options.asset_data) { reject('Error while addTrack track options.asset_data is required but is null'); } else { var exist_asset_data = fs.existsSync(options.asset_data); if (DEBUG_MODE_ON) { console.log("addTrack, exist_asset_data, ", exist_asset_data); } if (exist_asset_data) { form.append('track[asset_data]', fs.createReadStream(options.asset_data)); } else { reject('Error addTrack could not find options.asset_data --> fs.createReadStream(options.asset_data): ' + exist_asset_data); } } form.getLength(function (err, length) { fetch('https://api.soundcloud.com/tracks', { method: 'POST', body: form, headers: {'content-length': length} }).then(function (res) { return res.json(); }).then(function (json) { if (DEBUG_MODE_ON) { console.log('addTrack successful'); } resolve(json); }).catch(function (e) { reject(e); }); }); }); }
javascript
function addTrack(options) { return new Promise(function (resolve, reject) { var form = new FormData(); form.append('format', 'json'); if (!options.title) { reject('Error while addTrack track options.title is required but is null'); } else { form.append('track[title]', options.title); } if (!options.description) { reject('Error while addTrack track options.description is required but is null'); } else { form.append('track[description]', options.description); } if (!options.genre) { reject('Error while addTrack track options.genre is required but is null'); } else { form.append('track[genre]', options.genre); } var exist_artwork_data = fs.existsSync(options.artwork_data); if (exist_artwork_data) { form.append('track[artwork_data]', fs.createReadStream(options.artwork_data)); } if (options.tag_list) { form.append('track[tag_list]', options.tag_list); } form.append('track[sharing]', options.sharing); if (!options.oauth_token) { reject('Error while addTrack track oauth_token is required but is null'); } else { form.append('oauth_token', options.oauth_token); } if (!options.asset_data) { reject('Error while addTrack track options.asset_data is required but is null'); } else { var exist_asset_data = fs.existsSync(options.asset_data); if (DEBUG_MODE_ON) { console.log("addTrack, exist_asset_data, ", exist_asset_data); } if (exist_asset_data) { form.append('track[asset_data]', fs.createReadStream(options.asset_data)); } else { reject('Error addTrack could not find options.asset_data --> fs.createReadStream(options.asset_data): ' + exist_asset_data); } } form.getLength(function (err, length) { fetch('https://api.soundcloud.com/tracks', { method: 'POST', body: form, headers: {'content-length': length} }).then(function (res) { return res.json(); }).then(function (json) { if (DEBUG_MODE_ON) { console.log('addTrack successful'); } resolve(json); }).catch(function (e) { reject(e); }); }); }); }
[ "function", "addTrack", "(", "options", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "var", "form", "=", "new", "FormData", "(", ")", ";", "form", ".", "append", "(", "'format'", ",", "'json'", ")", ";", "if", "(", "!", "options", ".", "title", ")", "{", "reject", "(", "'Error while addTrack track options.title is required but is null'", ")", ";", "}", "else", "{", "form", ".", "append", "(", "'track[title]'", ",", "options", ".", "title", ")", ";", "}", "if", "(", "!", "options", ".", "description", ")", "{", "reject", "(", "'Error while addTrack track options.description is required but is null'", ")", ";", "}", "else", "{", "form", ".", "append", "(", "'track[description]'", ",", "options", ".", "description", ")", ";", "}", "if", "(", "!", "options", ".", "genre", ")", "{", "reject", "(", "'Error while addTrack track options.genre is required but is null'", ")", ";", "}", "else", "{", "form", ".", "append", "(", "'track[genre]'", ",", "options", ".", "genre", ")", ";", "}", "var", "exist_artwork_data", "=", "fs", ".", "existsSync", "(", "options", ".", "artwork_data", ")", ";", "if", "(", "exist_artwork_data", ")", "{", "form", ".", "append", "(", "'track[artwork_data]'", ",", "fs", ".", "createReadStream", "(", "options", ".", "artwork_data", ")", ")", ";", "}", "if", "(", "options", ".", "tag_list", ")", "{", "form", ".", "append", "(", "'track[tag_list]'", ",", "options", ".", "tag_list", ")", ";", "}", "form", ".", "append", "(", "'track[sharing]'", ",", "options", ".", "sharing", ")", ";", "if", "(", "!", "options", ".", "oauth_token", ")", "{", "reject", "(", "'Error while addTrack track oauth_token is required but is null'", ")", ";", "}", "else", "{", "form", ".", "append", "(", "'oauth_token'", ",", "options", ".", "oauth_token", ")", ";", "}", "if", "(", "!", "options", ".", "asset_data", ")", "{", "reject", "(", "'Error while addTrack track options.asset_data is required but is null'", ")", ";", "}", "else", "{", "var", "exist_asset_data", "=", "fs", ".", "existsSync", "(", "options", ".", "asset_data", ")", ";", "if", "(", "DEBUG_MODE_ON", ")", "{", "console", ".", "log", "(", "\"addTrack, exist_asset_data, \"", ",", "exist_asset_data", ")", ";", "}", "if", "(", "exist_asset_data", ")", "{", "form", ".", "append", "(", "'track[asset_data]'", ",", "fs", ".", "createReadStream", "(", "options", ".", "asset_data", ")", ")", ";", "}", "else", "{", "reject", "(", "'Error addTrack could not find options.asset_data ", "+", "exist_asset_data", ")", ";", "}", "}", "form", ".", "getLength", "(", "function", "(", "err", ",", "length", ")", "{", "fetch", "(", "'https://api.soundcloud.com/tracks'", ",", "{", "method", ":", "'POST'", ",", "body", ":", "form", ",", "headers", ":", "{", "'content-length'", ":", "length", "}", "}", ")", ".", "then", "(", "function", "(", "res", ")", "{", "return", "res", ".", "json", "(", ")", ";", "}", ")", ".", "then", "(", "function", "(", "json", ")", "{", "if", "(", "DEBUG_MODE_ON", ")", "{", "console", ".", "log", "(", "'addTrack successful'", ")", ";", "}", "resolve", "(", "json", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "e", ")", "{", "reject", "(", "e", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Add a new track @param options @param cb @returns {*}
[ "Add", "a", "new", "track" ]
b52461cdb6cafbe84c3b7ff367196fb03ad27afd
https://github.com/thomasmodeneis/soundcloudnodejs/blob/b52461cdb6cafbe84c3b7ff367196fb03ad27afd/soundcloudnodejs.js#L28-L104
train
thomasmodeneis/soundcloudnodejs
soundcloudnodejs.js
removeAllTracks
function removeAllTracks(tracks, token, count, callback) { var track = tracks[count]; if (!track) { return callback('done'); } var options = { id: track.id, oauth_token: token.oauth_token }; removeTrack(options).then(function (track) { if (DEBUG_MODE_ON) { console.log('removeTrack, ', track); } count = count + 1; removeAllTracks(tracks, token, count, callback) }).catch(function (err) { console.log('ERROR: removeTrack, ', err); count = count + 1; removeAllTracks(tracks, token, count, callback) }) }
javascript
function removeAllTracks(tracks, token, count, callback) { var track = tracks[count]; if (!track) { return callback('done'); } var options = { id: track.id, oauth_token: token.oauth_token }; removeTrack(options).then(function (track) { if (DEBUG_MODE_ON) { console.log('removeTrack, ', track); } count = count + 1; removeAllTracks(tracks, token, count, callback) }).catch(function (err) { console.log('ERROR: removeTrack, ', err); count = count + 1; removeAllTracks(tracks, token, count, callback) }) }
[ "function", "removeAllTracks", "(", "tracks", ",", "token", ",", "count", ",", "callback", ")", "{", "var", "track", "=", "tracks", "[", "count", "]", ";", "if", "(", "!", "track", ")", "{", "return", "callback", "(", "'done'", ")", ";", "}", "var", "options", "=", "{", "id", ":", "track", ".", "id", ",", "oauth_token", ":", "token", ".", "oauth_token", "}", ";", "removeTrack", "(", "options", ")", ".", "then", "(", "function", "(", "track", ")", "{", "if", "(", "DEBUG_MODE_ON", ")", "{", "console", ".", "log", "(", "'removeTrack, '", ",", "track", ")", ";", "}", "count", "=", "count", "+", "1", ";", "removeAllTracks", "(", "tracks", ",", "token", ",", "count", ",", "callback", ")", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "console", ".", "log", "(", "'ERROR: removeTrack, '", ",", "err", ")", ";", "count", "=", "count", "+", "1", ";", "removeAllTracks", "(", "tracks", ",", "token", ",", "count", ",", "callback", ")", "}", ")", "}" ]
Remove all tracks for a account. @param tracks @param token @param count @param callback
[ "Remove", "all", "tracks", "for", "a", "account", "." ]
b52461cdb6cafbe84c3b7ff367196fb03ad27afd
https://github.com/thomasmodeneis/soundcloudnodejs/blob/b52461cdb6cafbe84c3b7ff367196fb03ad27afd/soundcloudnodejs.js#L147-L170
train
thomasmodeneis/soundcloudnodejs
soundcloudnodejs.js
searchTrack_q
function searchTrack_q(options) { return new Promise(function (resolve, reject) { if (!options.oauth_token) { reject(new Error('Error searchTrack_q oauth_token is required and is null ')); } else { if (!options.q) { reject(new Error('Error searchTrack_q options.q is required and is null')); } else { var uri = 'https://api.soundcloud.com/me/tracks?format=json&oauth_token=' + options.oauth_token + '&q=' + options.q; if (DEBUG_MODE_ON) { console.log("searchTrack_q URI, ", uri); } request.getAsync(uri, {timeout: 10000}).spread(function (response, body) { //console.log('searchTrack_q successful',body); try { //console.log(body.toString('utf8')) resolve(JSON.parse(body.toString('utf8'))); } catch (e) { if (DEBUG_MODE_ON) { console.log('Error while searchTrack_q track: ', e); } reject(e); } }).catch(function (e) { if (DEBUG_MODE_ON) { console.log('Error while searchTrack_q track: ', e); } reject(e); }); } } }); }
javascript
function searchTrack_q(options) { return new Promise(function (resolve, reject) { if (!options.oauth_token) { reject(new Error('Error searchTrack_q oauth_token is required and is null ')); } else { if (!options.q) { reject(new Error('Error searchTrack_q options.q is required and is null')); } else { var uri = 'https://api.soundcloud.com/me/tracks?format=json&oauth_token=' + options.oauth_token + '&q=' + options.q; if (DEBUG_MODE_ON) { console.log("searchTrack_q URI, ", uri); } request.getAsync(uri, {timeout: 10000}).spread(function (response, body) { //console.log('searchTrack_q successful',body); try { //console.log(body.toString('utf8')) resolve(JSON.parse(body.toString('utf8'))); } catch (e) { if (DEBUG_MODE_ON) { console.log('Error while searchTrack_q track: ', e); } reject(e); } }).catch(function (e) { if (DEBUG_MODE_ON) { console.log('Error while searchTrack_q track: ', e); } reject(e); }); } } }); }
[ "function", "searchTrack_q", "(", "options", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "if", "(", "!", "options", ".", "oauth_token", ")", "{", "reject", "(", "new", "Error", "(", "'Error searchTrack_q oauth_token is required and is null '", ")", ")", ";", "}", "else", "{", "if", "(", "!", "options", ".", "q", ")", "{", "reject", "(", "new", "Error", "(", "'Error searchTrack_q options.q is required and is null'", ")", ")", ";", "}", "else", "{", "var", "uri", "=", "'https://api.soundcloud.com/me/tracks?format=json&oauth_token='", "+", "options", ".", "oauth_token", "+", "'&q='", "+", "options", ".", "q", ";", "if", "(", "DEBUG_MODE_ON", ")", "{", "console", ".", "log", "(", "\"searchTrack_q URI, \"", ",", "uri", ")", ";", "}", "request", ".", "getAsync", "(", "uri", ",", "{", "timeout", ":", "10000", "}", ")", ".", "spread", "(", "function", "(", "response", ",", "body", ")", "{", "try", "{", "resolve", "(", "JSON", ".", "parse", "(", "body", ".", "toString", "(", "'utf8'", ")", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "DEBUG_MODE_ON", ")", "{", "console", ".", "log", "(", "'Error while searchTrack_q track: '", ",", "e", ")", ";", "}", "reject", "(", "e", ")", ";", "}", "}", ")", ".", "catch", "(", "function", "(", "e", ")", "{", "if", "(", "DEBUG_MODE_ON", ")", "{", "console", ".", "log", "(", "'Error while searchTrack_q track: '", ",", "e", ")", ";", "}", "reject", "(", "e", ")", ";", "}", ")", ";", "}", "}", "}", ")", ";", "}" ]
Search for a track @param options @returns {bluebird|exports|module.exports}
[ "Search", "for", "a", "track" ]
b52461cdb6cafbe84c3b7ff367196fb03ad27afd
https://github.com/thomasmodeneis/soundcloudnodejs/blob/b52461cdb6cafbe84c3b7ff367196fb03ad27afd/soundcloudnodejs.js#L213-L247
train
thomasmodeneis/soundcloudnodejs
soundcloudnodejs.js
resolveUri
function resolveUri(options) { return new Promise(function (resolve, reject) { if (!options.client_id) { reject(new Error('Error resolveUri options.client_id is required but is null')); } else { if (!options.uri) { throw new Error('Error resolveUri options.uri is required and is: ' + options.uri); } else { var uri = 'http://api.soundcloud.com/resolve.json?url=' + options.uri + '&client_id=' + options.client_id; request.getAsync(uri, {timeout: 10000}).spread(function (response) { if (!response.body || response.body.indexOf('404') !== -1) { if (DEBUG_MODE_ON) { console.log('Error while resolveUri track: '); } reject(new Error('Error while resolveUri track: ')); } else { if (DEBUG_MODE_ON) { console.log('resolveUri successful'); } try { resolve(JSON.parse(response.body.toString('utf8'))); } catch (e) { if (DEBUG_MODE_ON) { console.log('Error while resolveUri track: ' + e); } reject(new Error('Error while resolveUri track: ' + e)); } } }).catch(function (e) { if (DEBUG_MODE_ON) { console.log('Error while resolveUri track: ', e); } reject(e); }); } } }); }
javascript
function resolveUri(options) { return new Promise(function (resolve, reject) { if (!options.client_id) { reject(new Error('Error resolveUri options.client_id is required but is null')); } else { if (!options.uri) { throw new Error('Error resolveUri options.uri is required and is: ' + options.uri); } else { var uri = 'http://api.soundcloud.com/resolve.json?url=' + options.uri + '&client_id=' + options.client_id; request.getAsync(uri, {timeout: 10000}).spread(function (response) { if (!response.body || response.body.indexOf('404') !== -1) { if (DEBUG_MODE_ON) { console.log('Error while resolveUri track: '); } reject(new Error('Error while resolveUri track: ')); } else { if (DEBUG_MODE_ON) { console.log('resolveUri successful'); } try { resolve(JSON.parse(response.body.toString('utf8'))); } catch (e) { if (DEBUG_MODE_ON) { console.log('Error while resolveUri track: ' + e); } reject(new Error('Error while resolveUri track: ' + e)); } } }).catch(function (e) { if (DEBUG_MODE_ON) { console.log('Error while resolveUri track: ', e); } reject(e); }); } } }); }
[ "function", "resolveUri", "(", "options", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "if", "(", "!", "options", ".", "client_id", ")", "{", "reject", "(", "new", "Error", "(", "'Error resolveUri options.client_id is required but is null'", ")", ")", ";", "}", "else", "{", "if", "(", "!", "options", ".", "uri", ")", "{", "throw", "new", "Error", "(", "'Error resolveUri options.uri is required and is: '", "+", "options", ".", "uri", ")", ";", "}", "else", "{", "var", "uri", "=", "'http://api.soundcloud.com/resolve.json?url='", "+", "options", ".", "uri", "+", "'&client_id='", "+", "options", ".", "client_id", ";", "request", ".", "getAsync", "(", "uri", ",", "{", "timeout", ":", "10000", "}", ")", ".", "spread", "(", "function", "(", "response", ")", "{", "if", "(", "!", "response", ".", "body", "||", "response", ".", "body", ".", "indexOf", "(", "'404'", ")", "!==", "-", "1", ")", "{", "if", "(", "DEBUG_MODE_ON", ")", "{", "console", ".", "log", "(", "'Error while resolveUri track: '", ")", ";", "}", "reject", "(", "new", "Error", "(", "'Error while resolveUri track: '", ")", ")", ";", "}", "else", "{", "if", "(", "DEBUG_MODE_ON", ")", "{", "console", ".", "log", "(", "'resolveUri successful'", ")", ";", "}", "try", "{", "resolve", "(", "JSON", ".", "parse", "(", "response", ".", "body", ".", "toString", "(", "'utf8'", ")", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "DEBUG_MODE_ON", ")", "{", "console", ".", "log", "(", "'Error while resolveUri track: '", "+", "e", ")", ";", "}", "reject", "(", "new", "Error", "(", "'Error while resolveUri track: '", "+", "e", ")", ")", ";", "}", "}", "}", ")", ".", "catch", "(", "function", "(", "e", ")", "{", "if", "(", "DEBUG_MODE_ON", ")", "{", "console", ".", "log", "(", "'Error while resolveUri track: '", ",", "e", ")", ";", "}", "reject", "(", "e", ")", ";", "}", ")", ";", "}", "}", "}", ")", ";", "}" ]
Resolve a URI @param options @returns {bluebird|exports|module.exports}
[ "Resolve", "a", "URI" ]
b52461cdb6cafbe84c3b7ff367196fb03ad27afd
https://github.com/thomasmodeneis/soundcloudnodejs/blob/b52461cdb6cafbe84c3b7ff367196fb03ad27afd/soundcloudnodejs.js#L254-L295
train
thomasmodeneis/soundcloudnodejs
soundcloudnodejs.js
addTrackToNewPlaylist
function addTrackToNewPlaylist(options) { return new Promise(function (resolve, reject) { var form = new FormData(); form.append('format', 'json'); if (!options.tracks) { return reject('Error while addTrackToNewPlaylist options.tracks is null'); } else { _.each(options.tracks, function (track) { form.append('playlist[tracks][][id]', track.id); }); } if (!options.title) { return reject('Error while addTrackToNewPlaylist options.title is null'); } else { form.append('playlist[title]', options.title); } if (!options.sharing) { return reject('Error while addTrackToNewPlaylist options.sharing is null'); } else { form.append('playlist[sharing]', options.sharing); } if (!options.oauth_token) { return reject('Error while addTrackToNewPlaylist options.oauth_token is null'); } else { form.append('oauth_token', options.oauth_token); } form.getLength(function (err, length) { fetch(`https://api.soundcloud.com/playlists?oauth_token=${options.oauth_token}`, { method: 'POST', body: form, headers: {'content-length': length} }).then(function (res) { if (res.status === 201) { if (DEBUG_MODE_ON) { console.log(`INFO: addTrackToNewPlaylist, OK -> ${res.statusCode}.`); } return res.json(); } else { return null; } }).then(function (json) { if (!json) { reject(); } else { if (DEBUG_MODE_ON) { console.log('INFO: addTrack successful'); } resolve(json); } }).catch(function (e) { reject(e); }); }); }); }
javascript
function addTrackToNewPlaylist(options) { return new Promise(function (resolve, reject) { var form = new FormData(); form.append('format', 'json'); if (!options.tracks) { return reject('Error while addTrackToNewPlaylist options.tracks is null'); } else { _.each(options.tracks, function (track) { form.append('playlist[tracks][][id]', track.id); }); } if (!options.title) { return reject('Error while addTrackToNewPlaylist options.title is null'); } else { form.append('playlist[title]', options.title); } if (!options.sharing) { return reject('Error while addTrackToNewPlaylist options.sharing is null'); } else { form.append('playlist[sharing]', options.sharing); } if (!options.oauth_token) { return reject('Error while addTrackToNewPlaylist options.oauth_token is null'); } else { form.append('oauth_token', options.oauth_token); } form.getLength(function (err, length) { fetch(`https://api.soundcloud.com/playlists?oauth_token=${options.oauth_token}`, { method: 'POST', body: form, headers: {'content-length': length} }).then(function (res) { if (res.status === 201) { if (DEBUG_MODE_ON) { console.log(`INFO: addTrackToNewPlaylist, OK -> ${res.statusCode}.`); } return res.json(); } else { return null; } }).then(function (json) { if (!json) { reject(); } else { if (DEBUG_MODE_ON) { console.log('INFO: addTrack successful'); } resolve(json); } }).catch(function (e) { reject(e); }); }); }); }
[ "function", "addTrackToNewPlaylist", "(", "options", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "var", "form", "=", "new", "FormData", "(", ")", ";", "form", ".", "append", "(", "'format'", ",", "'json'", ")", ";", "if", "(", "!", "options", ".", "tracks", ")", "{", "return", "reject", "(", "'Error while addTrackToNewPlaylist options.tracks is null'", ")", ";", "}", "else", "{", "_", ".", "each", "(", "options", ".", "tracks", ",", "function", "(", "track", ")", "{", "form", ".", "append", "(", "'playlist[tracks][][id]'", ",", "track", ".", "id", ")", ";", "}", ")", ";", "}", "if", "(", "!", "options", ".", "title", ")", "{", "return", "reject", "(", "'Error while addTrackToNewPlaylist options.title is null'", ")", ";", "}", "else", "{", "form", ".", "append", "(", "'playlist[title]'", ",", "options", ".", "title", ")", ";", "}", "if", "(", "!", "options", ".", "sharing", ")", "{", "return", "reject", "(", "'Error while addTrackToNewPlaylist options.sharing is null'", ")", ";", "}", "else", "{", "form", ".", "append", "(", "'playlist[sharing]'", ",", "options", ".", "sharing", ")", ";", "}", "if", "(", "!", "options", ".", "oauth_token", ")", "{", "return", "reject", "(", "'Error while addTrackToNewPlaylist options.oauth_token is null'", ")", ";", "}", "else", "{", "form", ".", "append", "(", "'oauth_token'", ",", "options", ".", "oauth_token", ")", ";", "}", "form", ".", "getLength", "(", "function", "(", "err", ",", "length", ")", "{", "fetch", "(", "`", "${", "options", ".", "oauth_token", "}", "`", ",", "{", "method", ":", "'POST'", ",", "body", ":", "form", ",", "headers", ":", "{", "'content-length'", ":", "length", "}", "}", ")", ".", "then", "(", "function", "(", "res", ")", "{", "if", "(", "res", ".", "status", "===", "201", ")", "{", "if", "(", "DEBUG_MODE_ON", ")", "{", "console", ".", "log", "(", "`", "${", "res", ".", "statusCode", "}", "`", ")", ";", "}", "return", "res", ".", "json", "(", ")", ";", "}", "else", "{", "return", "null", ";", "}", "}", ")", ".", "then", "(", "function", "(", "json", ")", "{", "if", "(", "!", "json", ")", "{", "reject", "(", ")", ";", "}", "else", "{", "if", "(", "DEBUG_MODE_ON", ")", "{", "console", ".", "log", "(", "'INFO: addTrack successful'", ")", ";", "}", "resolve", "(", "json", ")", ";", "}", "}", ")", ".", "catch", "(", "function", "(", "e", ")", "{", "reject", "(", "e", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Add track to new playlist @param options @param cb @returns {*}
[ "Add", "track", "to", "new", "playlist" ]
b52461cdb6cafbe84c3b7ff367196fb03ad27afd
https://github.com/thomasmodeneis/soundcloudnodejs/blob/b52461cdb6cafbe84c3b7ff367196fb03ad27afd/soundcloudnodejs.js#L377-L436
train
thomasmodeneis/soundcloudnodejs
soundcloudnodejs.js
getPlaylist
function getPlaylist(options) { return new Promise(function (resolve, reject) { if (!options.oauth_token) { reject(new Error('Error oauth_token is required, but is null')); } else { var uri = 'https://api.soundcloud.com/me/playlists?format=json&oauth_token=' + options.oauth_token; request.getAsync(uri, {timeout: 10000}).spread(function (response, body) { try { var tracks = _.map(JSON.parse(body.toString('utf8')), function (track) { return track; }); if (DEBUG_MODE_ON) { console.log('getPlaylist successful'); } resolve(tracks); } catch (e) { if (DEBUG_MODE_ON) { console.log('Error while getPlaylist track: ', e); } reject(e); } }).catch(function (e) { if (DEBUG_MODE_ON) { console.log('Error while getPlaylist track: ' + e); } reject(e); }) } }); }
javascript
function getPlaylist(options) { return new Promise(function (resolve, reject) { if (!options.oauth_token) { reject(new Error('Error oauth_token is required, but is null')); } else { var uri = 'https://api.soundcloud.com/me/playlists?format=json&oauth_token=' + options.oauth_token; request.getAsync(uri, {timeout: 10000}).spread(function (response, body) { try { var tracks = _.map(JSON.parse(body.toString('utf8')), function (track) { return track; }); if (DEBUG_MODE_ON) { console.log('getPlaylist successful'); } resolve(tracks); } catch (e) { if (DEBUG_MODE_ON) { console.log('Error while getPlaylist track: ', e); } reject(e); } }).catch(function (e) { if (DEBUG_MODE_ON) { console.log('Error while getPlaylist track: ' + e); } reject(e); }) } }); }
[ "function", "getPlaylist", "(", "options", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "if", "(", "!", "options", ".", "oauth_token", ")", "{", "reject", "(", "new", "Error", "(", "'Error oauth_token is required, but is null'", ")", ")", ";", "}", "else", "{", "var", "uri", "=", "'https://api.soundcloud.com/me/playlists?format=json&oauth_token='", "+", "options", ".", "oauth_token", ";", "request", ".", "getAsync", "(", "uri", ",", "{", "timeout", ":", "10000", "}", ")", ".", "spread", "(", "function", "(", "response", ",", "body", ")", "{", "try", "{", "var", "tracks", "=", "_", ".", "map", "(", "JSON", ".", "parse", "(", "body", ".", "toString", "(", "'utf8'", ")", ")", ",", "function", "(", "track", ")", "{", "return", "track", ";", "}", ")", ";", "if", "(", "DEBUG_MODE_ON", ")", "{", "console", ".", "log", "(", "'getPlaylist successful'", ")", ";", "}", "resolve", "(", "tracks", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "DEBUG_MODE_ON", ")", "{", "console", ".", "log", "(", "'Error while getPlaylist track: '", ",", "e", ")", ";", "}", "reject", "(", "e", ")", ";", "}", "}", ")", ".", "catch", "(", "function", "(", "e", ")", "{", "if", "(", "DEBUG_MODE_ON", ")", "{", "console", ".", "log", "(", "'Error while getPlaylist track: '", "+", "e", ")", ";", "}", "reject", "(", "e", ")", ";", "}", ")", "}", "}", ")", ";", "}" ]
Get a playlist @param options @returns {bluebird|exports|module.exports}
[ "Get", "a", "playlist" ]
b52461cdb6cafbe84c3b7ff367196fb03ad27afd
https://github.com/thomasmodeneis/soundcloudnodejs/blob/b52461cdb6cafbe84c3b7ff367196fb03ad27afd/soundcloudnodejs.js#L443-L473
train
thomasmodeneis/soundcloudnodejs
soundcloudnodejs.js
getToken
function getToken(options) { return new Promise(function (resolve) { var curl_options = { 'url': 'https://api.soundcloud.com/oauth2/token', 'method': 'POST', verbose: true, encoding: 'utf8', data: options, timeout: 10000 }; curlrequest.request(curl_options, function (err, data, meta) { if (err) { if (DEBUG_MODE_ON) { console.log("Error: getToken, ", err, data, meta); } resolve(null); } else if (!data) { if (DEBUG_MODE_ON) { console.log("Error: getToken, data is null ", data, meta); } resolve(null); } else { try { resolve(JSON.parse(data), meta); } catch (e) { if (DEBUG_MODE_ON) { console.log("Error: getToken, catch, ", e, data, meta); } resolve(null); } } }); }); }
javascript
function getToken(options) { return new Promise(function (resolve) { var curl_options = { 'url': 'https://api.soundcloud.com/oauth2/token', 'method': 'POST', verbose: true, encoding: 'utf8', data: options, timeout: 10000 }; curlrequest.request(curl_options, function (err, data, meta) { if (err) { if (DEBUG_MODE_ON) { console.log("Error: getToken, ", err, data, meta); } resolve(null); } else if (!data) { if (DEBUG_MODE_ON) { console.log("Error: getToken, data is null ", data, meta); } resolve(null); } else { try { resolve(JSON.parse(data), meta); } catch (e) { if (DEBUG_MODE_ON) { console.log("Error: getToken, catch, ", e, data, meta); } resolve(null); } } }); }); }
[ "function", "getToken", "(", "options", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "var", "curl_options", "=", "{", "'url'", ":", "'https://api.soundcloud.com/oauth2/token'", ",", "'method'", ":", "'POST'", ",", "verbose", ":", "true", ",", "encoding", ":", "'utf8'", ",", "data", ":", "options", ",", "timeout", ":", "10000", "}", ";", "curlrequest", ".", "request", "(", "curl_options", ",", "function", "(", "err", ",", "data", ",", "meta", ")", "{", "if", "(", "err", ")", "{", "if", "(", "DEBUG_MODE_ON", ")", "{", "console", ".", "log", "(", "\"Error: getToken, \"", ",", "err", ",", "data", ",", "meta", ")", ";", "}", "resolve", "(", "null", ")", ";", "}", "else", "if", "(", "!", "data", ")", "{", "if", "(", "DEBUG_MODE_ON", ")", "{", "console", ".", "log", "(", "\"Error: getToken, data is null \"", ",", "data", ",", "meta", ")", ";", "}", "resolve", "(", "null", ")", ";", "}", "else", "{", "try", "{", "resolve", "(", "JSON", ".", "parse", "(", "data", ")", ",", "meta", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "DEBUG_MODE_ON", ")", "{", "console", ".", "log", "(", "\"Error: getToken, catch, \"", ",", "e", ",", "data", ",", "meta", ")", ";", "}", "resolve", "(", "null", ")", ";", "}", "}", "}", ")", ";", "}", ")", ";", "}" ]
Get a fresh token, need to be use with caution as SoundCloud will allow you to get very few tokens Its smart to save your tokens and re-use it along your code @param options @returns {bluebird|exports|module.exports}
[ "Get", "a", "fresh", "token", "need", "to", "be", "use", "with", "caution", "as", "SoundCloud", "will", "allow", "you", "to", "get", "very", "few", "tokens", "Its", "smart", "to", "save", "your", "tokens", "and", "re", "-", "use", "it", "along", "your", "code" ]
b52461cdb6cafbe84c3b7ff367196fb03ad27afd
https://github.com/thomasmodeneis/soundcloudnodejs/blob/b52461cdb6cafbe84c3b7ff367196fb03ad27afd/soundcloudnodejs.js#L558-L593
train
thanhpk/vue2-strap
dist/dropdownhover.js
DropdownHover
function DropdownHover($elem, options) { var args = arguments; // Is the first parameter an object (options), or was omitted, // instantiate a new instance of the plugin. if (options === undefined || typeof options === 'object') { // This allows the plugin to be called with $.fn.bootstrapDropdownHover(); if (!$.contains(document, $($elem)[0])) { $('[data-toggle="dropdown"]').each(function (index, item) { // For each nested select, instantiate the plugin console.log(item, $elem); $(item).bootstrapDropdownHover(options); }); } return $elem.each(function () { // If this is not a select if (!$(this).hasClass('dropdown-toggle') || $(this).data('toggle') !== 'dropdown') { $('[data-toggle="dropdown"]', this).each(function (index, item) { // For each nested select, instantiate the plugin DropdownHover($(item), options); }); } else if (!$.data(this, 'plugin_' + pluginName)) { // Only allow the plugin to be instantiated once so we check // that the element has no plugin instantiation yet // if it has no instance, create a new one, pass options to our // plugin constructor, // and store the plugin instance in the elements jQuery data object. $.data(this, 'plugin_' + pluginName, new BootstrapDropdownHover(this, options)); } }); // If the first parameter is a string and it doesn't start // with an underscore or "contains" the `init`-function, // treat this as a call to a public method. } else if (typeof options === 'string' && options[0] !== '_' && options !== 'init') { // Cache the method call to make it possible to return a value var returns; $elem.each(function () { var instance = $.data(this, 'plugin_' + pluginName); // Tests that there's already a plugin-instance and checks that // the requested public method exists if (instance instanceof BootstrapDropdownHover && typeof instance[options] === 'function') { // Call the method of our plugin instance, and pass // it the supplied arguments. returns = instance[options] .apply(instance, Array.prototype.slice.call(args, 1)); } }); // If the earlier cached method gives a value back return the value, // otherwise return this to preserve chainability. return returns !== undefined ? returns : this; } return undefined; }
javascript
function DropdownHover($elem, options) { var args = arguments; // Is the first parameter an object (options), or was omitted, // instantiate a new instance of the plugin. if (options === undefined || typeof options === 'object') { // This allows the plugin to be called with $.fn.bootstrapDropdownHover(); if (!$.contains(document, $($elem)[0])) { $('[data-toggle="dropdown"]').each(function (index, item) { // For each nested select, instantiate the plugin console.log(item, $elem); $(item).bootstrapDropdownHover(options); }); } return $elem.each(function () { // If this is not a select if (!$(this).hasClass('dropdown-toggle') || $(this).data('toggle') !== 'dropdown') { $('[data-toggle="dropdown"]', this).each(function (index, item) { // For each nested select, instantiate the plugin DropdownHover($(item), options); }); } else if (!$.data(this, 'plugin_' + pluginName)) { // Only allow the plugin to be instantiated once so we check // that the element has no plugin instantiation yet // if it has no instance, create a new one, pass options to our // plugin constructor, // and store the plugin instance in the elements jQuery data object. $.data(this, 'plugin_' + pluginName, new BootstrapDropdownHover(this, options)); } }); // If the first parameter is a string and it doesn't start // with an underscore or "contains" the `init`-function, // treat this as a call to a public method. } else if (typeof options === 'string' && options[0] !== '_' && options !== 'init') { // Cache the method call to make it possible to return a value var returns; $elem.each(function () { var instance = $.data(this, 'plugin_' + pluginName); // Tests that there's already a plugin-instance and checks that // the requested public method exists if (instance instanceof BootstrapDropdownHover && typeof instance[options] === 'function') { // Call the method of our plugin instance, and pass // it the supplied arguments. returns = instance[options] .apply(instance, Array.prototype.slice.call(args, 1)); } }); // If the earlier cached method gives a value back return the value, // otherwise return this to preserve chainability. return returns !== undefined ? returns : this; } return undefined; }
[ "function", "DropdownHover", "(", "$elem", ",", "options", ")", "{", "var", "args", "=", "arguments", ";", "if", "(", "options", "===", "undefined", "||", "typeof", "options", "===", "'object'", ")", "{", "if", "(", "!", "$", ".", "contains", "(", "document", ",", "$", "(", "$elem", ")", "[", "0", "]", ")", ")", "{", "$", "(", "'[data-toggle=\"dropdown\"]'", ")", ".", "each", "(", "function", "(", "index", ",", "item", ")", "{", "console", ".", "log", "(", "item", ",", "$elem", ")", ";", "$", "(", "item", ")", ".", "bootstrapDropdownHover", "(", "options", ")", ";", "}", ")", ";", "}", "return", "$elem", ".", "each", "(", "function", "(", ")", "{", "if", "(", "!", "$", "(", "this", ")", ".", "hasClass", "(", "'dropdown-toggle'", ")", "||", "$", "(", "this", ")", ".", "data", "(", "'toggle'", ")", "!==", "'dropdown'", ")", "{", "$", "(", "'[data-toggle=\"dropdown\"]'", ",", "this", ")", ".", "each", "(", "function", "(", "index", ",", "item", ")", "{", "DropdownHover", "(", "$", "(", "item", ")", ",", "options", ")", ";", "}", ")", ";", "}", "else", "if", "(", "!", "$", ".", "data", "(", "this", ",", "'plugin_'", "+", "pluginName", ")", ")", "{", "$", ".", "data", "(", "this", ",", "'plugin_'", "+", "pluginName", ",", "new", "BootstrapDropdownHover", "(", "this", ",", "options", ")", ")", ";", "}", "}", ")", ";", "}", "else", "if", "(", "typeof", "options", "===", "'string'", "&&", "options", "[", "0", "]", "!==", "'_'", "&&", "options", "!==", "'init'", ")", "{", "var", "returns", ";", "$elem", ".", "each", "(", "function", "(", ")", "{", "var", "instance", "=", "$", ".", "data", "(", "this", ",", "'plugin_'", "+", "pluginName", ")", ";", "if", "(", "instance", "instanceof", "BootstrapDropdownHover", "&&", "typeof", "instance", "[", "options", "]", "===", "'function'", ")", "{", "returns", "=", "instance", "[", "options", "]", ".", "apply", "(", "instance", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "args", ",", "1", ")", ")", ";", "}", "}", ")", ";", "return", "returns", "!==", "undefined", "?", "returns", ":", "this", ";", "}", "return", "undefined", ";", "}" ]
A really lightweight plugin wrapper around the constructor, preventing against multiple instantiations
[ "A", "really", "lightweight", "plugin", "wrapper", "around", "the", "constructor", "preventing", "against", "multiple", "instantiations" ]
44e93ce3c985b31aa7ccb11f67842914ddb6013f
https://github.com/thanhpk/vue2-strap/blob/44e93ce3c985b31aa7ccb11f67842914ddb6013f/dist/dropdownhover.js#L162-L220
train
Barandis/xduce
src/modules/reduction.js
init
function init(collection) { switch (true) { case isImplemented(collection, 'init'): return collection[p.init]; case isString(collection): return () => ''; case isArray(collection): return () => []; case isObject(collection): return () => ({}); case isFunction(collection): return () => { throw Error('init not available'); }; default: return null; } }
javascript
function init(collection) { switch (true) { case isImplemented(collection, 'init'): return collection[p.init]; case isString(collection): return () => ''; case isArray(collection): return () => []; case isObject(collection): return () => ({}); case isFunction(collection): return () => { throw Error('init not available'); }; default: return null; } }
[ "function", "init", "(", "collection", ")", "{", "switch", "(", "true", ")", "{", "case", "isImplemented", "(", "collection", ",", "'init'", ")", ":", "return", "collection", "[", "p", ".", "init", "]", ";", "case", "isString", "(", "collection", ")", ":", "return", "(", ")", "=>", "''", ";", "case", "isArray", "(", "collection", ")", ":", "return", "(", ")", "=>", "[", "]", ";", "case", "isObject", "(", "collection", ")", ":", "return", "(", ")", "=>", "(", "{", "}", ")", ";", "case", "isFunction", "(", "collection", ")", ":", "return", "(", ")", "=>", "{", "throw", "Error", "(", "'init not available'", ")", ";", "}", ";", "default", ":", "return", "null", ";", "}", "}" ]
Returns an init function for a collection. This is a function that returns a new, empty instance of the collection in question. If the collection doesn't support reduction, `null` is returned. This makes conditionals a bit easier to work with. In order to support the conversion of functions into reducers, function support is also provided. @private @param {*} collection A collection to create an init function for. This can be anything that supports the ES2015 iteration protocol, a plain object, a pre-ES2015 string or array, or a function. @return {module:xduce~init} A function that, when called, returns an initial version of the provided collection. If the provided collection is not iterable, then `null` is returned.
[ "Returns", "an", "init", "function", "for", "a", "collection", ".", "This", "is", "a", "function", "that", "returns", "a", "new", "empty", "instance", "of", "the", "collection", "in", "question", ".", "If", "the", "collection", "doesn", "t", "support", "reduction", "null", "is", "returned", ".", "This", "makes", "conditionals", "a", "bit", "easier", "to", "work", "with", "." ]
b454f154f7663475670d4802e28e98ade8c468e7
https://github.com/Barandis/xduce/blob/b454f154f7663475670d4802e28e98ade8c468e7/src/modules/reduction.js#L49-L66
train
Barandis/xduce
src/modules/reduction.js
step
function step(collection) { switch (true) { case isImplemented(collection, 'step'): return collection[p.step]; case isString(collection): return (acc, input) => { const value = isKvFormObject(input) ? input.v : input; return acc + value; }; case isArray(collection): return (acc, input) => { const value = isKvFormObject(input) ? { [input.k]: input.v } : input; acc.push(value); return acc; }; case isObject(collection): return (acc, input) => { let value = input; if (isKvFormObject(input)) { // if the object is kv-form, change the object from { k: key, v: value } to { key: value } value = { [input.k]: input.v }; } else if (!isObject(input)) { // if the input isn't an object at all, turn it into an object with a key based on what's already in the // accumulator let max = -1; for (const k1 in acc) { const knum = parseInt(k1); if (knum > max) { max = knum; } } value = { [max + 1]: input }; } for (const k2 in value) { if (value.hasOwnProperty(k2)) { acc[k2] = value[k2]; } } return acc; }; case isFunction(collection): return (acc, input) => collection(acc, input); default: return null; } }
javascript
function step(collection) { switch (true) { case isImplemented(collection, 'step'): return collection[p.step]; case isString(collection): return (acc, input) => { const value = isKvFormObject(input) ? input.v : input; return acc + value; }; case isArray(collection): return (acc, input) => { const value = isKvFormObject(input) ? { [input.k]: input.v } : input; acc.push(value); return acc; }; case isObject(collection): return (acc, input) => { let value = input; if (isKvFormObject(input)) { // if the object is kv-form, change the object from { k: key, v: value } to { key: value } value = { [input.k]: input.v }; } else if (!isObject(input)) { // if the input isn't an object at all, turn it into an object with a key based on what's already in the // accumulator let max = -1; for (const k1 in acc) { const knum = parseInt(k1); if (knum > max) { max = knum; } } value = { [max + 1]: input }; } for (const k2 in value) { if (value.hasOwnProperty(k2)) { acc[k2] = value[k2]; } } return acc; }; case isFunction(collection): return (acc, input) => collection(acc, input); default: return null; } }
[ "function", "step", "(", "collection", ")", "{", "switch", "(", "true", ")", "{", "case", "isImplemented", "(", "collection", ",", "'step'", ")", ":", "return", "collection", "[", "p", ".", "step", "]", ";", "case", "isString", "(", "collection", ")", ":", "return", "(", "acc", ",", "input", ")", "=>", "{", "const", "value", "=", "isKvFormObject", "(", "input", ")", "?", "input", ".", "v", ":", "input", ";", "return", "acc", "+", "value", ";", "}", ";", "case", "isArray", "(", "collection", ")", ":", "return", "(", "acc", ",", "input", ")", "=>", "{", "const", "value", "=", "isKvFormObject", "(", "input", ")", "?", "{", "[", "input", ".", "k", "]", ":", "input", ".", "v", "}", ":", "input", ";", "acc", ".", "push", "(", "value", ")", ";", "return", "acc", ";", "}", ";", "case", "isObject", "(", "collection", ")", ":", "return", "(", "acc", ",", "input", ")", "=>", "{", "let", "value", "=", "input", ";", "if", "(", "isKvFormObject", "(", "input", ")", ")", "{", "value", "=", "{", "[", "input", ".", "k", "]", ":", "input", ".", "v", "}", ";", "}", "else", "if", "(", "!", "isObject", "(", "input", ")", ")", "{", "let", "max", "=", "-", "1", ";", "for", "(", "const", "k1", "in", "acc", ")", "{", "const", "knum", "=", "parseInt", "(", "k1", ")", ";", "if", "(", "knum", ">", "max", ")", "{", "max", "=", "knum", ";", "}", "}", "value", "=", "{", "[", "max", "+", "1", "]", ":", "input", "}", ";", "}", "for", "(", "const", "k2", "in", "value", ")", "{", "if", "(", "value", ".", "hasOwnProperty", "(", "k2", ")", ")", "{", "acc", "[", "k2", "]", "=", "value", "[", "k2", "]", ";", "}", "}", "return", "acc", ";", "}", ";", "case", "isFunction", "(", "collection", ")", ":", "return", "(", "acc", ",", "input", ")", "=>", "collection", "(", "acc", ",", "input", ")", ";", "default", ":", "return", "null", ";", "}", "}" ]
Returns a step function for a collection. This is a function that takes an accumulator and a value and returns the result of reducing the value into the accumulator. If the collection doesn't support reduction, `null` is returned. The returned function itself simply reduces the input into the target collection without modifying it. In order to support the conversion of functions into reducers, function support is also provided. @private @param {*} collection A collection to create a step function for. This can be anything that supports the ES2015 iteration protocol, a plain object, a pre-ES2015 string or array, or a function. @return {module:xduce~step} A reduction function for the provided collection that simply adds an element to the target collection without modifying it. If the provided collection is not iterable, `null` is returned.
[ "Returns", "a", "step", "function", "for", "a", "collection", ".", "This", "is", "a", "function", "that", "takes", "an", "accumulator", "and", "a", "value", "and", "returns", "the", "result", "of", "reducing", "the", "value", "into", "the", "accumulator", ".", "If", "the", "collection", "doesn", "t", "support", "reduction", "null", "is", "returned", ".", "The", "returned", "function", "itself", "simply", "reduces", "the", "input", "into", "the", "target", "collection", "without", "modifying", "it", "." ]
b454f154f7663475670d4802e28e98ade8c468e7
https://github.com/Barandis/xduce/blob/b454f154f7663475670d4802e28e98ade8c468e7/src/modules/reduction.js#L82-L134
train
Barandis/xduce
src/modules/reduction.js
result
function result(collection) { switch (true) { case isImplemented(collection, 'result'): return collection[p.result]; case isString(collection): case isArray(collection): case isObject(collection): case isFunction(collection): return value => value; default: return null; } }
javascript
function result(collection) { switch (true) { case isImplemented(collection, 'result'): return collection[p.result]; case isString(collection): case isArray(collection): case isObject(collection): case isFunction(collection): return value => value; default: return null; } }
[ "function", "result", "(", "collection", ")", "{", "switch", "(", "true", ")", "{", "case", "isImplemented", "(", "collection", ",", "'result'", ")", ":", "return", "collection", "[", "p", ".", "result", "]", ";", "case", "isString", "(", "collection", ")", ":", "case", "isArray", "(", "collection", ")", ":", "case", "isObject", "(", "collection", ")", ":", "case", "isFunction", "(", "collection", ")", ":", "return", "value", "=>", "value", ";", "default", ":", "return", "null", ";", "}", "}" ]
Returns a result function for a collection. This is a function that performs any final processing that should be done on the result of a reduction. If the collection doesn't support reduction, `null` is returned. In order to support the conversion of functions into reducers, function support is also provided. @private @param {*} collection A collection to create a step function for. This can be anything that supports the ES2015 iteration protocol, a plain object, a pre-ES2015 string or array, or a function. @return {module:xduce~result} A function that, when given a reduced collection, produces the final output. If the provided collection is not iterable, `null` will be returned.
[ "Returns", "a", "result", "function", "for", "a", "collection", ".", "This", "is", "a", "function", "that", "performs", "any", "final", "processing", "that", "should", "be", "done", "on", "the", "result", "of", "a", "reduction", ".", "If", "the", "collection", "doesn", "t", "support", "reduction", "null", "is", "returned", "." ]
b454f154f7663475670d4802e28e98ade8c468e7
https://github.com/Barandis/xduce/blob/b454f154f7663475670d4802e28e98ade8c468e7/src/modules/reduction.js#L149-L161
train
theodoreb/jquarry
lib/target/scan-jquery-use.js
quickCheckMethods
function quickCheckMethods(tokens, JQAPI) { var JQMethods = _.pluck(JQAPI, 'method'); var identifiers = _.where(tokens, {type: 'Identifier'}); return !!_.intersection(JQMethods, _.pluck(identifiers, 'value')).length; }
javascript
function quickCheckMethods(tokens, JQAPI) { var JQMethods = _.pluck(JQAPI, 'method'); var identifiers = _.where(tokens, {type: 'Identifier'}); return !!_.intersection(JQMethods, _.pluck(identifiers, 'value')).length; }
[ "function", "quickCheckMethods", "(", "tokens", ",", "JQAPI", ")", "{", "var", "JQMethods", "=", "_", ".", "pluck", "(", "JQAPI", ",", "'method'", ")", ";", "var", "identifiers", "=", "_", ".", "where", "(", "tokens", ",", "{", "type", ":", "'Identifier'", "}", ")", ";", "return", "!", "!", "_", ".", "intersection", "(", "JQMethods", ",", "_", ".", "pluck", "(", "identifiers", ",", "'value'", ")", ")", ".", "length", ";", "}" ]
Check any jQuery method appears in the code. @param tokens @param JQAPI @returns {boolean}
[ "Check", "any", "jQuery", "method", "appears", "in", "the", "code", "." ]
7066617e592e9c8ae3acb23cc0f1a3847654a6c0
https://github.com/theodoreb/jquarry/blob/7066617e592e9c8ae3acb23cc0f1a3847654a6c0/lib/target/scan-jquery-use.js#L26-L30
train
fritbot/fb-opt-quotes
import_quotes.js
checkFinished
function checkFinished() { if ((import_count + dupe_count) % 100 === 0) { console.log('Imported', import_count + dupe_count, '/', quote_count); } // Once we're done, show the stats and tell the bot to shutdown. // Since the bot is fully async-aware itself, it won't shut down unless explicitly told to. if (finished_reading && quote_count === import_count + dupe_count) { console.log('\nQuotes in file:', quote_count); console.log('Quotes imported:', import_count); console.log('Duplicate quotes:', dupe_count); bot.shutdown(); } }
javascript
function checkFinished() { if ((import_count + dupe_count) % 100 === 0) { console.log('Imported', import_count + dupe_count, '/', quote_count); } // Once we're done, show the stats and tell the bot to shutdown. // Since the bot is fully async-aware itself, it won't shut down unless explicitly told to. if (finished_reading && quote_count === import_count + dupe_count) { console.log('\nQuotes in file:', quote_count); console.log('Quotes imported:', import_count); console.log('Duplicate quotes:', dupe_count); bot.shutdown(); } }
[ "function", "checkFinished", "(", ")", "{", "if", "(", "(", "import_count", "+", "dupe_count", ")", "%", "100", "===", "0", ")", "{", "console", ".", "log", "(", "'Imported'", ",", "import_count", "+", "dupe_count", ",", "'/'", ",", "quote_count", ")", ";", "}", "if", "(", "finished_reading", "&&", "quote_count", "===", "import_count", "+", "dupe_count", ")", "{", "console", ".", "log", "(", "'\\nQuotes in file:'", ",", "\\n", ")", ";", "quote_count", "console", ".", "log", "(", "'Quotes imported:'", ",", "import_count", ")", ";", "console", ".", "log", "(", "'Duplicate quotes:'", ",", "dupe_count", ")", ";", "}", "}" ]
Check if all async DB calls have finished. Output if so.
[ "Check", "if", "all", "async", "DB", "calls", "have", "finished", ".", "Output", "if", "so", "." ]
f5cc97d95b3a2bfbe619c026fa70b61556dc9757
https://github.com/fritbot/fb-opt-quotes/blob/f5cc97d95b3a2bfbe619c026fa70b61556dc9757/import_quotes.js#L58-L71
train
rxaviers/builder-amd-css
bower_components/require-css/normalize.js
absoluteURI
function absoluteURI(uri, base) { if (uri.substr(0, 2) == './') uri = uri.substr(2); // absolute urls are left in tact if (uri.match(absUrlRegEx) || uri.match(protocolRegEx)) return uri; var baseParts = base.split('/'); var uriParts = uri.split('/'); baseParts.pop(); while (curPart = uriParts.shift()) if (curPart == '..') baseParts.pop(); else baseParts.push(curPart); return baseParts.join('/'); }
javascript
function absoluteURI(uri, base) { if (uri.substr(0, 2) == './') uri = uri.substr(2); // absolute urls are left in tact if (uri.match(absUrlRegEx) || uri.match(protocolRegEx)) return uri; var baseParts = base.split('/'); var uriParts = uri.split('/'); baseParts.pop(); while (curPart = uriParts.shift()) if (curPart == '..') baseParts.pop(); else baseParts.push(curPart); return baseParts.join('/'); }
[ "function", "absoluteURI", "(", "uri", ",", "base", ")", "{", "if", "(", "uri", ".", "substr", "(", "0", ",", "2", ")", "==", "'./'", ")", "uri", "=", "uri", ".", "substr", "(", "2", ")", ";", "if", "(", "uri", ".", "match", "(", "absUrlRegEx", ")", "||", "uri", ".", "match", "(", "protocolRegEx", ")", ")", "return", "uri", ";", "var", "baseParts", "=", "base", ".", "split", "(", "'/'", ")", ";", "var", "uriParts", "=", "uri", ".", "split", "(", "'/'", ")", ";", "baseParts", ".", "pop", "(", ")", ";", "while", "(", "curPart", "=", "uriParts", ".", "shift", "(", ")", ")", "if", "(", "curPart", "==", "'..'", ")", "baseParts", ".", "pop", "(", ")", ";", "else", "baseParts", ".", "push", "(", "curPart", ")", ";", "return", "baseParts", ".", "join", "(", "'/'", ")", ";", "}" ]
given a relative URI, calculate the absolute URI
[ "given", "a", "relative", "URI", "calculate", "the", "absolute", "URI" ]
ad225d76285a68c5fa750fdc31e2f2c7365aa8b3
https://github.com/rxaviers/builder-amd-css/blob/ad225d76285a68c5fa750fdc31e2f2c7365aa8b3/bower_components/require-css/normalize.js#L63-L83
train