_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
27
233k
language
stringclasses
1 value
meta_information
dict
q5700
getModifiedFiles
train
async function getModifiedFiles() { return (await execa.stdout('git', ['ls-files',
javascript
{ "resource": "" }
q5701
level
train
function level (pipe, cachedLevelOf, taskKey) { var taskLevel = 0 var parentsOf = parents.bind(null, pipe) if (typeof cachedLevelOf[taskKey] === 'number') { return cachedLevelOf[taskKey] } function computeLevel (parentTaskKey)
javascript
{ "resource": "" }
q5702
train
function (callback) { fs.readFile(clientSecretPath, function processClientSecrets(err, content) { if (err) { debug('Error loading
javascript
{ "resource": "" }
q5703
isDflowFun
train
function isDflowFun (f) { var isFunction = typeof f === 'function' var hasFuncsObject = typeof f.funcs === 'object' var hasGraphObject = typeof f.graph === 'object' var hasValidGraph = true if (!isFunction || !hasFuncsObject || !hasGraphObject) return false if (isFunction
javascript
{ "resource": "" }
q5704
Formats
train
function Formats(options) { options = options || {}; this.debugConstructor = options.debug || debug; this.debug = this.debugConstructor('oada:formats'); this.errorConstructor = options.error || debug;
javascript
{ "resource": "" }
q5705
inputArgs
train
function inputArgs (outs, pipe, taskKey) { var args = [] var inputPipesOf = inputPipes.bind(null, pipe) function populateArg (inputPipe) { var index = inputPipe[2] || 0 var value
javascript
{ "resource": "" }
q5706
evaluate
train
function evaluate(request, policies, engines) { const decisions = policies.map((policy) => (
javascript
{ "resource": "" }
q5707
toGemoji
train
function toGemoji(node) { var value = toString(node) var info = (unicodes[value] || emoticons[value]
javascript
{ "resource": "" }
q5708
toEmoji
train
function toEmoji(node) { var value = toString(node) var info = (shortcodes[value] || emoticons[value]
javascript
{ "resource": "" }
q5709
minifyTemplate
train
function minifyTemplate(file) { try { let minifiedFile = htmlMinifier.minify(file, { collapseWhitespace: true, caseSensitive: true, removeComments: true
javascript
{ "resource": "" }
q5710
transpile
train
function transpile() { return exec('node_modules/.bin/ngc -p tsconfig.json', function (err, stdout, stderr) { console.log(stdout);
javascript
{ "resource": "" }
q5711
clearValue
train
function clearValue() { clearSelectedItem(); setInputClearButton(); if (self.parentForm &&
javascript
{ "resource": "" }
q5712
handleSearchText
train
function handleSearchText(searchText, previousSearchText) { self.index = -1; // do nothing on init if (searchText === previousSearchText) return; else if (self.selectedItem && self.displayProperty1) { setLoading(false); if (self.selectedItem[self.displayProperty1] !== searchText) {
javascript
{ "resource": "" }
q5713
selectedItemChange
train
function selectedItemChange(selectedItem, previousSelectedItem) { if (selectedItem) { if (self.displayProperty1) { self.searchText = selectedItem[self.displayProperty1]; } if (self.parentForm && self.parentForm !== null) { self.parentForm.$setDirty(); } }
javascript
{ "resource": "" }
q5714
updateScroll
train
function updateScroll() { if (!self.element.li[0]) return; var height = self.element.li[0].offsetHeight, top = height * self.index, bot = top +
javascript
{ "resource": "" }
q5715
handleUniqueResult
train
function handleUniqueResult(results) { var res = [], flag = {}; for (var i = 0; i<results.length; i++) {
javascript
{ "resource": "" }
q5716
convertArrayToObject
train
function convertArrayToObject(array) { var temp = []; array.forEach(function (text) { temp.push({
javascript
{ "resource": "" }
q5717
train
function(retCode) { retCode = (typeof retCode !== 'undefined') ? retCode : 0; if (server) { if (shutdownInProgress) { return; } shutdownInProgress = true; console.info('Shutting down gracefully...'); server.close(function() { console.info('Closed out remaining connections'); process.exit(retCode); }); setTimeout(function() {
javascript
{ "resource": "" }
q5718
injectArguments
train
function injectArguments (funcs, task, args) { function getArgument (index) { return args[index] } /** * Inject arguments. */ function inject (taskKey) { var funcName = task[taskKey] if (funcName === 'arguments') { funcs[funcName] = function getArguments () { return args } } else {
javascript
{ "resource": "" }
q5719
inject
train
function inject (taskKey) { var funcName = task[taskKey] if (funcName === 'arguments') { funcs[funcName] = function getArguments () { return args } } else {
javascript
{ "resource": "" }
q5720
injectGlobals
train
function injectGlobals (funcs, task) { /** * Inject task */ function inject (taskKey) { var taskName = task[taskKey] // Do not overwrite a function if already defined. // For example, console.log cannot be used as is, it must binded to console. if (typeof funcs[taskName] === 'function') return // Skip also reserved keywords. if (reservedKeys.indexOf(taskName) > -1) return var globalValue = walkGlobal(taskName)
javascript
{ "resource": "" }
q5721
renderExample
train
function renderExample (divId, example) { var graph = graphs[example] var canvas = new Canvas(divId, {
javascript
{ "resource": "" }
q5722
injectReferences
train
function injectReferences (funcs, task) { /** * Inject task. * * @param {String} taskKey */ function inject (taskKey) { var referenceName = null var referencedFunction = null var taskName = task[taskKey] /** * Inject reference. */ function reference () { return referencedFunction } if (regexReference.test(taskName)) { referenceName = taskName.substring(1)
javascript
{ "resource": "" }
q5723
inject
train
function inject (taskKey) { var referenceName = null var referencedFunction = null var taskName = task[taskKey] /** * Inject reference. */ function reference () { return referencedFunction } if (regexReference.test(taskName)) { referenceName = taskName.substring(1) if (typeof funcs[referenceName] === 'function') { referencedFunction = funcs[referenceName]
javascript
{ "resource": "" }
q5724
injectStrings
train
function injectStrings (funcs, task) { /** * Inject a function that returns a string. */ function inject (taskKey) { var taskName = task[taskKey] if (regexQuoted.test(taskName)) { funcs[taskName] =
javascript
{ "resource": "" }
q5725
inject
train
function inject (taskKey) { var taskName = task[taskKey] if (regexQuoted.test(taskName)) { funcs[taskName] = function () {
javascript
{ "resource": "" }
q5726
request
train
function request(url, options, callback) { var debug = require('debug')('wayback:http'); debug('req', url); callback = typeof callback === 'undefined' ? options : callback; // @see https://www.npmjs.com/package/fetch var stream = new fetch(url, typeof options === 'object' ? options : undefined); stream.on('error', function(err)
javascript
{ "resource": "" }
q5727
filePersister
train
function filePersister(filepath) { var self = this; this.initialized = false; this.filepath = filepath; /** * Check to see if the specified file path is available. * @returns A promise appropriately resolving or rejecting. */ this.start = function() { if (!this.initialized) { return fsp.emptyDir(this.filepath) .then(function() { self.initialized = true; return Promise.resolve('User has permissions to write to that file.'); }) .catch(function(err) { return Promise.reject('User does not have permissions to write to that folder.'); }); } return Promise.reject('Error: Persister already initialized.'); }; /** * Save the passed state to the file. * @param {Object} passedState - State to be saved in the file. * @returns A promise resolving to an appropriate success message or an error message. */ this.save = function(brain, package) { var filepath = this.filepath; if (this.initialized) { return fsp.remove(filepath + '/' + package + '.txt') .then(function(){ return fsp.writeFile(filepath + '/' + package + '.txt', JSON.stringify(brain));
javascript
{ "resource": "" }
q5728
addAction
train
function addAction(action, ctrl) { this.addActionIcon(action, ctrl); if (!this.actionExists(action, ctrl)) { ctrl.actionListService.requiredActionsList.splice(action.index, 0, action.name); ctrl.actionListService.actionsToIndex[action.name] = action.index;
javascript
{ "resource": "" }
q5729
removeAction
train
function removeAction(action, ctrl) { if (this.actionExists(action, ctrl)) { this.removeActionIcon(action, ctrl); delete ctrl.actionListService.actionsToIndex[action.name]; delete ctrl.actionListService.onToggle[action.name]; var i = ctrl.actionListService.actionsToDisplay.indexOf(action.name);
javascript
{ "resource": "" }
q5730
dataFormatter
train
function dataFormatter(data) { var instanceInfoArray = []; var instanceInfoObject = {}; var reservations = data.Reservations; for (var reservation in reservations) { var instances = reservations[reservation].Instances; for (var instance in instances) { var tags = instances[instance].Tags; for (var tag in tags) { if (tags[tag].Key === 'Name') { instanceInfoObject = _.assign(instanceInfoObject, {Name: tags[tag].Value});
javascript
{ "resource": "" }
q5731
Extractor
train
function Extractor(ac , options) { EventEmitter.call(this); var self = this; self.matchers = []; self.vars = ac || {}; self.options = options || {}; self.watchers = []; self._listen = function (car, file) { car.once('end', function () { self.emit('end', self.vars); }); car.on('line', function (line) { var i; var firstMatch = true; for (i = 0; i < self.matchers.length; i++) { var matcher = self.matchers[i]; var
javascript
{ "resource": "" }
q5732
wildcards
train
function wildcards(f, cb, ctxt) { var starmatch = f.match(/([^*]*)\*.*/); if (!starmatch) { //keep async process.nextTick(function () { cb.apply(ctxt, [f]); }); return; } var basedirPath = starmatch[1].split(/\//); basedirPath.pop(); var wkdir = basedirPath.join('/'); //console.log('search base : %s', wkdir); var r = f.substring(wkdir.length + 1); //console.log('match pattern: %s', r); glob(r, {
javascript
{ "resource": "" }
q5733
Censoring
train
function Censoring() { /** * The string to replaces found matches with. Defaults to *** * * @type {String} */ this.replacementString = '***'; /** * The color used for highlighting * * @type {string} */ this.highlightColor = 'F2B8B8'; /** * Holds the currently matched text. * * @type {{replace: string, hasMatches: boolean}} */ this.currentMatch = { replace: '', hasMatches: false, matches: [] }; /** * The available patterns. These are as follows: * [name] [description] * - long_number ; Matches long, consecutive numbers * - phone_number ; Matches phone numbers. * - email_address ; Matches email addresses in many formats. * - url ; Matches URL patterns/ * - words ; Finds words, even when in disguise. * * @type {{long_number: {pattern: RegExp, enabled: boolean}, phone_number: {pattern: RegExp, enabled: boolean}, email_address: {pattern: RegExp, enabled: boolean}, url: {pattern: RegExp, enabled: boolean}, words: {enabled: boolean, pattern: Array}}} */ this.patterns = { long_number: { pattern: /\d{8,}/, enabled: false }, phone_number: { pattern: /([+-]?[\d]{1,}[\d\s-]+|\([\d]+\))[-\d.\s]{8,}/gi, enabled: false }, email_address: { pattern: /[\w._%+-]+(@|\[at\]|\(at\))[\w.-]+(\.|\[dot\]|\(dot\)|\(punt\)|\[punt\])[a-zA-Z]{2,4}/gi,
javascript
{ "resource": "" }
q5734
train
function (filters) { if (!this.isArray(filters)) { throw 'Invalid filters type supplied. Expected Array.'; } for (var
javascript
{ "resource": "" }
q5735
train
function (words) { if (!this.isArray(words)) { throw 'Invalid type supplied for addFilterWords. Expected array.'; } for (var
javascript
{ "resource": "" }
q5736
train
function (word) { var pattern = '', any = '[^a-z0-9]?', last = false, character; for (var i = 0; i < word.length; i++) { last = i === (word.length - 1); character = word.charAt(i); if (typeof this.map1337[character] === 'undefined') { pattern += (character + (!last ? any : '')); continue; } if (typeof this.map1337[character] === 'string') { pattern += ('((' + character + '|' + this.map1337[character] + ')' + (!last ? any : '') + ')'); continue;
javascript
{ "resource": "" }
q5737
train
function (str, highlight) { this.currentMatch.replace = this.filterString(str, highlight); this.currentMatch.hasMatches =
javascript
{ "resource": "" }
q5738
train
function (str, highlight) { highlight = highlight || false; var self = this; var highlightColor = this.highlightColor; var replace = function (str, pattern) { if (!highlight) { return str.replace(pattern, function (match) { self.currentMatch.matches.push(match); return self.replacementString; }); } return str.replace(pattern, function (match) { self.currentMatch.matches.push(match); return '<span style="background: #' + highlightColor + ';">' + match + '</span>'; }); }.bind(this); if (typeof str !== 'string') { throw 'Invalid "str" type supplied in filterString. Expected string.'; } for (var p in this.patterns) { if (!this.patterns[p].enabled) { continue; } if (this.patterns[p].pattern instanceof RegExp) { str = replace(str, this.patterns[p].pattern); continue;
javascript
{ "resource": "" }
q5739
addCssExtension
train
function addCssExtension(args, styleExts, extensions) { for (let x = 0, len = args.length; x < len; x++) {
javascript
{ "resource": "" }
q5740
train
function (values, next) { const api = path.basename(__filename, '.js').toLowerCase(); if (strapi.api.hasOwnProperty(api) && _.size(strapi.api[api].templates)) { const template = _.includes(strapi.api[api].templates, values.template) ? values.template : strapi.models[api].defaultTemplate; // Set template with correct value values.template = template; // Merge model type with template validations const templateAttributes = _.merge(_.pick(strapi.models[api].attributes, 'lang'), strapi.api[api].templates[template].attributes); const err = []; _.forEach(templateAttributes, function (rules, key) { if (values.hasOwnProperty(key) || key === 'lang') { if (key === 'lang') { // Set lang with correct value
javascript
{ "resource": "" }
q5741
getItem
train
function getItem(ATR) { var item; while( item === undefined ) { item = slist[ATR]; if(!ATR) break;
javascript
{ "resource": "" }
q5742
Log
train
function Log(keyboardInfo) { var log = keyboardInfo.querySelector('ul') var st = keyboardInfo.querySelector('.statistic') var totalAvgTime = 0 var totalCount = 0 return function (key, statistic) { var count = statistic.count var average = statistic.average totalCount = totalCount + 1 totalAvgTime = totalAvgTime + statistic.average totalAvg = +(totalAvgTime/totalCount).toFixed(2) || 0 var li = document.createElement('li')
javascript
{ "resource": "" }
q5743
extname
train
function extname(ext) { var str = ext.charAt(0) === '.' ? ext.slice(1) : ext; if (str
javascript
{ "resource": "" }
q5744
buildQuery
train
function buildQuery(query, builder = new Builder()) { for (let i = 0; i < query.length; i++) { const method = query[i] if (Array.isArray(method)) { builder.and(buildQuery(method, new NonCapture())) continue } if (!method instanceof Method) { // At this point, there should only be methods left, since all parameters are already taken care of. // If that's not the case, something didn't work out. throw new SyntaxException(`Unexpected statement: ${method}`) } const parameters = [] // If there are parameters, walk through them and apply them if they don't start a new method. while (query[i + 1] && !(query[i + 1] instanceof Method)) { parameters.push(query[i + 1]) // Since the parameters will be appended to the method object, they are already parsed and can be // removed from further parsing. Don't use unset to keep keys incrementing. query.splice(i + 1, 1) } try { // Now, append that method to the builder object.
javascript
{ "resource": "" }
q5745
setClassName
train
function setClassName(element, cssClass) { cssClass = snippet.isArray(cssClass) ? cssClass.join(' ') : cssClass; cssClass = trim(cssClass); if (snippet.isUndefined(element.className.baseVal)) {
javascript
{ "resource": "" }
q5746
getNamespace
train
function getNamespace(file, path) { const files = namespaces.filter(ns => ns.meta.filename === file && ns.meta.path === path); if (files.length > 0) { return files[files.length - 1]; } const paths = namespaces.filter(ns => isIndex(ns.meta.filename) && isParent(ns.meta.path, path));
javascript
{ "resource": "" }
q5747
expandPropertyNameGlobs
train
function expandPropertyNameGlobs(object, globPatterns) { const result = []; if (!globPatterns.length) return result; const arrayGroupPattern = globPatterns[0]; const indexOfArrayGroup = arrayGroupPattern.indexOf('[]'); if (indexOfArrayGroup !== -1) { const {arrayProp, arrayPropName} = getArrayProperty(object, arrayGroupPattern, indexOfArrayGroup); arrayProp.forEach((v, i) => { const pp = `${arrayPropName}[${i}]`; const propertyGroup = []; for (let i = 1; i < globPatterns.length; i++) { const pattern = `${pp}.${globPatterns[i]}`; propertyGroup.push(pattern); } result.push(propertyGroup); }); return result; } for (let pattern of globPatterns) { let indexOfGlob = pattern.indexOf('*'); if (indexOfGlob === -1) { result.push(pattern); } else {
javascript
{ "resource": "" }
q5748
fromRpcSig
train
function fromRpcSig(flatSig) { const expandedSig = ethutil.fromRpcSig(flatSig); return { s: ethutil.bufferToHex(expandedSig.s),
javascript
{ "resource": "" }
q5749
isSignedBy
train
function isSignedBy(message, signature, address) { try { const ethMessage = ethHash(message); return
javascript
{ "resource": "" }
q5750
methodMatch
train
function methodMatch(part) { let maxMatch = null let maxMatchCount = 0 // Go through each mapper and check if the name matches. Then, take the highest match to avoid matching // 'any', if 'any character' was given, and so on. Object.keys(mapper).forEach((key) => { const regex = new RegExp(`^(${key.replace(' ', ') (')})`, 'i') const matches = part.match(regex) const count = matches ? matches.length : 0 if (count > maxMatchCount) { maxMatchCount = count
javascript
{ "resource": "" }
q5751
train
function () { // <<<<<< public var newMono, newMonoTo, toFirstOutSeg, fromRevSeg; for ( var i = 0, j = this.segments.length; i < j; i++) { newMono = this.segments[i]; if ( this.PolyLeftArr[newMono.chainId] ) { // preserve winding order newMonoTo = newMono.vTo; // target of segment newMono.mprev = newMono.sprev; // doubly linked list for monotone chains (sub-polygons)
javascript
{ "resource": "" }
q5752
train
function () { // <<<<<<<<<< public var normedMonoChains = this.polyData.getMonoSubPolys(); this.polyData.clearTriangles(); for ( var i=0; i<normedMonoChains.length; i++ ) { // loop through uni-y-monotone chains // => monoPosmin is next to monoPosmax (left or right) var monoPosmax = normedMonoChains[i]; var prevMono = monoPosmax.mprev; var nextMono = monoPosmax.mnext; if ( nextMono.mnext == prevMono ) {
javascript
{ "resource": "" }
q5753
Server
train
function Server (options, origins) { var me = this; this.origins = origins || ['*:*']; this.port = 843; this.log = console.log; // merge `this` with the options Object.keys(options).forEach(function (key) { me[key] && (me[key] = options[key]) }); // create the net server this.socket = net.createServer(function createServer (socket) { socket.on('error', function socketError () { me.responder.call(me, socket); }); me.responder.call(me, socket); }); // Listen for errors as the port might be blocked because we do not have root priv. this.socket.on('error', function serverError (err) { // Special and common case error handling if (err.errno == 13) { me.log && me.log( 'Unable to listen to port `' + me.port + '` as your Node.js instance does not have root privileges. ' + ( me.server ? 'The Flash Policy File requests will only be served inline over the supplied HTTP server. Inline serving is slower than a dedicated server instance.' : 'No fallback server supplied, we will be unable to answer Flash Policy File requests.' ) ); me.emit('connect_failed', err); me.socket.removeAllListeners(); delete me.socket; } else { me.log && me.log('FlashPolicyFileServer received an error
javascript
{ "resource": "" }
q5754
determineNonceFromReceipt
train
function determineNonceFromReceipt(receipt, address) { const {sender, recipient}
javascript
{ "resource": "" }
q5755
train
function(seriesCallback) { async.eachLimit(groupedPinIds, 50, function(groupOfPinIds, eachCallback) { var pinIdsString = groupOfPinIds.join(','); getCache(pinIdsString, true, function (cacheData) { if (cacheData === null) { get('http://api.pinterest.com/v3/pidgets/pins/info/?pin_ids=' + pinIdsString, true, function (response) { putCache(pinIdsString, JSON.stringify(response)); allPinsData = allPinsData.concat(response.data ? response.data : []); eachCallback(); return; });
javascript
{ "resource": "" }
q5756
train
function(seriesCallback) { var userBoardAlreadyAdded = {}; for(var i = 0; i < allPinsData.length; i++) { var pin = allPinsData[i]; if(pin.board) { var boardUrlParts = pin.board.url.split('/'); var user = boardUrlParts[1]; var board = boardUrlParts[2];
javascript
{ "resource": "" }
q5757
train
function(seriesCallback) { if(!obtainDates) { seriesCallback(); return; } var pinDateMaps = []; async.eachLimit(boards, 5, function(board, eachCallback) { getDatesForBoardPinsFromRss(board.user, board.board, function(result) { pinDateMaps.push(result); eachCallback(); }); }, function (err) { if(err) { throw err; } var pinDateMap = mergeMaps(pinDateMaps); for (var i = 0; i < allPinsData.length; i++) { allPinsData[i].created_at = null;
javascript
{ "resource": "" }
q5758
train
function(seriesCallback) { if(!obtainDates) { seriesCallback(); return; } getDatesForPinsFromScraping(pinsThatNeedScrapedDates, null, function (pinDateMap) { for (var i = 0; i < allPinsData.length; i++) { if (allPinsData[i].created_at == null && pinDateMap[allPinsData[i].id] && pinDateMap[allPinsData[i].id].date) { allPinsData[i].created_at = pinDateMap[allPinsData[i].id].date;
javascript
{ "resource": "" }
q5759
stash
train
function stash(storage, storageKey, key, value) { // get the squirrel storage object. var store = window.JSON.parse(storage.getItem(storageKey)); // if it doesn't exist, create an empty object. if (store === null) { store = {}; } // if a value isn't specified. if (isUndefined(value) || value === null) { // return the store value if the store value exists; otherwise, null. return !isUndefined(store[key]) ? store[key] : null; } // if a value is specified. // create an append object literal. var append = {};
javascript
{ "resource": "" }
q5760
createLiterallyObjects
train
function createLiterallyObjects(query, openPos, stringPositions) { const firstRaw = query.substr(0, openPos) const result = [firstRaw.trim()] let pointer = 0 stringPositions.forEach((stringPosition) => { if (!stringPosition.end) { throw new SyntaxException('Invalid string ending found.') } if (stringPosition.end < firstRaw.length) { // At least one string exists in first part, create a new object. // Remove the last part, since this wasn't parsed. result.pop() // Add part between pointer and string occurrence.
javascript
{ "resource": "" }
q5761
memorizeHandler
train
function memorizeHandler(element, type, keyFn, valueFn) { const map = safeEvent(element, type); let items = map.get(keyFn); if (items) {
javascript
{ "resource": "" }
q5762
bindEvent
train
function bindEvent(element, type, handler, context) { /** * Event handler * @param {Event} e - event object */ function eventHandler(e) { handler.call(context || element, e || window.event); } /** * Event handler for normalize mouseenter event * @param {MouseEvent} e - event object */ function mouseEnterHandler(e) { e = e || window.event; if (checkMouse(element, e)) { eventHandler(e); } } if ('addEventListener' in element) { if (type === 'mouseenter' || type === 'mouseleave') { type = (type === 'mouseenter') ? 'mouseover' : 'mouseout';
javascript
{ "resource": "" }
q5763
mouseEnterHandler
train
function mouseEnterHandler(e) { e = e || window.event;
javascript
{ "resource": "" }
q5764
unbindEvent
train
function unbindEvent(element, type, handler) { const events = safeEvent(element, type); const items = events.get(handler); if (!items) { return; } forgetHandler(element, type, handler); util.forEach(items, func => { if ('removeEventListener' in element) {
javascript
{ "resource": "" }
q5765
execute
train
function execute(context, action) { if (!remote) return fail(context, "Not connected to a server"); // prepare
javascript
{ "resource": "" }
q5766
list
train
function list(context, err, items, paths) { if (err) return fail(context, err); var long = context.options["l"]; if (typeof long === "undefined") long = (context.command.slice(-3) === "dir"); items.forEach(function (item) { if (item.filename == "." || item.filename == "..") return;
javascript
{ "resource": "" }
q5767
done
train
function done(context, err, message) { if (err) return fail(context, err); if (typeof message !==
javascript
{ "resource": "" }
q5768
fail
train
function fail(context, err) { var message; switch (err.code) { case "ENOENT": message = err.path + ": No such file or directory"; break; case "ENOSYS": message = "Command not supported";
javascript
{ "resource": "" }
q5769
umd
train
function umd() { let bundler = browserify(src, { debug: true, standalone: 'luhn' }) .transform(babelify) // .configure({ optional: ['runtime'] }) .bundle(); return bundler .pipe(source(pack.main)) // gives streaming vinyl file object .pipe(buffer()) // convert from streaming to buffered
javascript
{ "resource": "" }
q5770
min
train
function min() { return gulp.src(pack.main) .pipe(uglify())
javascript
{ "resource": "" }
q5771
subscribeToEvents
train
function subscribeToEvents() { const socket = _socket.get(this); function onEventApiError(error) { dbg('Event API connection error: ' + JSON.stringify(error)); } socket.on('pong', (latency) => { dbg(`Event API latency: ${latency} ms`); }); socket.on('connect_error', onEventApiError);
javascript
{ "resource": "" }
q5772
train
function(line) { // example: def bar(a, b) do // // (^\s*) begining of line // (def|defp) $1 public or private def // (.*?) $2 in betweend def ... do // \s* optional space // do opening keyword (bracket in JS) // \s*$ end of line var parts = line.match(/^(\s*)(defp\s|def\s)(.*?)\s*do\s*$/); if (!parts) return line; // ^( $1 // \s*[\w$]+ function name // ) // ( $2 optional params including parens // \( literal parens // (.*?) $3 just params // \)
javascript
{ "resource": "" }
q5773
train
function(line) { var newLine; // ex: [foo <- 1,2,3] // [ opening array // (.*) $1 array to concat into // (<-) $2 // (.*) $3 content to be merged // ] closing array var regexArr = /\[(.*)(\<\-)(.*)\]/; // ex: {foo <- foo: true, bar: 2} // { opening object // (.*) $1 obj to merge into // (<-) $2 // (.*) $3 content to be merged
javascript
{ "resource": "" }
q5774
train
function(line, index, lines) { var newLine; if (insideString('|>', line)) return line; // line does not have a one liner pipeline if (!line.match(/(\=|return)(.*?)(\|\>)/)) return line; // if next line has a pipe operator if (lines[index] && lines[index + 1].match(/^\s*\|\>/)) return line; // http://rubular.com/r/wiBJtf12Vn // (^.+?) $1 value to pipe // \s* optional spaces // (\|\>) $2 |> pipe operator // (.*?)$ $3 tail minus first pipe ($2) // var parts = line.match(/(^.+?)\s*(\|\>)(.*?)$/); var head = parts[1] var tail = parts[2].concat(parts[3]);
javascript
{ "resource": "" }
q5775
train
function(line) { //^ // (\s*) $1 opts leading spaces // ([\w$]+\s*) $2 variable name & trailing spaces // (\=) $3 division equals OR // \s* opt spaces // (.*?) rest of expression to assign // $ var parts = line.match(/^(\s*)([\w$]+)\s*(\=)\s*(.*?)$/); if (!parts)
javascript
{ "resource": "" }
q5776
magnify
train
function magnify( pageOffsetX, pageOffsetY, elementOffsetX, elementOffsetY, scale ) { if( supportsTransforms ) { var origin = pageOffsetX +'px '+ pageOffsetY +'px', transform = 'translate('+ -elementOffsetX +'px,'+ -elementOffsetY +'px) scale('+ scale +')'; document.body.style.transformOrigin = origin; document.body.style.OTransformOrigin = origin; document.body.style.msTransformOrigin = origin; document.body.style.MozTransformOrigin = origin; document.body.style.WebkitTransformOrigin = origin; document.body.style.transform = transform; document.body.style.OTransform = transform; document.body.style.msTransform = transform; document.body.style.MozTransform = transform; document.body.style.WebkitTransform = transform; } else { // Reset all values if( scale === 1 ) { document.body.style.position = ''; document.body.style.left = ''; document.body.style.top = ''; document.body.style.width = ''; document.body.style.height = '';
javascript
{ "resource": "" }
q5777
pan
train
function pan() { var range = 0.12, rangeX = window.innerWidth * range, rangeY = window.innerHeight * range, scrollOffset = getScrollOffset(); // Up if( mouseY < rangeY ) { window.scroll( scrollOffset.x, scrollOffset.y - ( 1 - ( mouseY / rangeY ) ) * ( 14 / level ) ); } // Down else if( mouseY > window.innerHeight - rangeY ) { window.scroll( scrollOffset.x, scrollOffset.y + ( 1 - ( window.innerHeight - mouseY ) / rangeY ) * ( 14 / level ) ); } //
javascript
{ "resource": "" }
q5778
train
function() { clearTimeout( panEngageTimeout ); clearInterval( panUpdateInterval ); var scrollOffset = getScrollOffset(); if( currentOptions &&
javascript
{ "resource": "" }
q5779
buildResponseCard
train
function buildResponseCard(title, subTitle, options) { let buttons = null; if (options != null) { buttons = []; for (let i = 0; i < Math.min(5, options.length); i++) { buttons.push(options[i]); } } return {
javascript
{ "resource": "" }
q5780
getAvailabilities
train
function getAvailabilities(date) { const dayOfWeek = parseLocalDate(date).getDay(); const availabilities = []; const availableProbability = 0.3; if (dayOfWeek === 1) { let startHour = 10; while (startHour <= 16) { if (Math.random() < availableProbability) { // Add an availability window for the given hour, with duration determined by another random number. const appointmentType = getRandomInt(1, 4);
javascript
{ "resource": "" }
q5781
getAvailabilitiesForDuration
train
function getAvailabilitiesForDuration(duration, availabilities) { const durationAvailabilities = []; let startTime = '10:00'; while (startTime !== '17:00') { if (availabilities.indexOf(startTime) !== -1) { if (duration === 30) { durationAvailabilities.push(startTime); }
javascript
{ "resource": "" }
q5782
buildAvailableTimeString
train
function buildAvailableTimeString(availabilities) { let prefix = 'We have availabilities at '; if (availabilities.length > 3) { prefix = 'We have plenty of availability, including '; } prefix += buildTimeOutputString(availabilities[0]); if (availabilities.length === 2)
javascript
{ "resource": "" }
q5783
buildOptions
train
function buildOptions(slot, appointmentType, date, bookingMap) { const dayStrings = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; if (slot === 'AppointmentType') { return [ { text: 'cleaning (30 min)', value: 'cleaning' }, { text: 'root canal (60 min)', value: 'root canal' }, { text: 'whitening (30 min)', value: 'whitening' }, ]; } else if (slot === 'Date') { // Return the next five weekdays. const options = []; const potentialDate = new Date(); while (options.length < 5) { potentialDate.setDate(potentialDate.getDate() + 1); if (potentialDate.getDay() > 0 && potentialDate.getDay() < 6) { options.push({ text: `${potentialDate.getMonth() + 1}-${potentialDate.getDate()} (${dayStrings[potentialDate.getDay()]})`, value: potentialDate.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' }) }); } } return options; } else if (slot === 'Time') { // Return the availabilities on the given date. if (!appointmentType || !date) { return null;
javascript
{ "resource": "" }
q5784
makeRequest
train
function makeRequest () { request = self.request.apply(null, args); requestMiddleware.use(request); request.on("response", function (response) { var contentEncoding, gzipper; //Only cache successful responses if (response.statusCode >= 200 && response.statusCode < 300) { response.on('error', function (error) { self.handleError(error); }); fs.writeFile(self.cacheDirectory + key + ".json", JSON.stringify(response.headers), function (error) { if (error) self.handleError(error); }); responseWriter = fs.createWriteStream(self.cacheDirectory + key); responseWriter.on('error', function (error) { self.handleError(error); }); contentEncoding = response.headers['content-encoding'] || ''; contentEncoding = contentEncoding.trim().toLowerCase(); if (contentEncoding === 'gzip') { response.on('error', function (error) { responseWriter.end(); }); response.pipe(responseWriter); } else { gzipper = zlib.createGzip();
javascript
{ "resource": "" }
q5785
dynamicLoad
train
function dynamicLoad(dynamicOptions, options, defaultOptions) { let loadableFn = Loadable let loadableOptions = defaultOptions if (typeof dynamicOptions.then === 'function') { // Support for direct import(), // eg: dynamic(import('../hello-world')) loadableOptions.loader = () => dynamicOptions } else if (typeof dynamicOptions === 'object') { // Support for having first argument being options, // eg: dynamic({loader: import('../hello-world')}) loadableOptions = { ...loadableOptions, ...dynamicOptions } } // Support for passing options, // eg: dynamic(import('../hello-world'), {loading: () => <p>Loading something</p>}) loadableOptions = { ...loadableOptions, ...options } // Support for `render` when using a mapping, // eg: `dynamic({ modules: () => {return {HelloWorld: import('../hello-world')}, render(props, loaded) {} } }) if (dynamicOptions.render) { loadableOptions.render = (loaded, props) => dynamicOptions.render(props, loaded) }
javascript
{ "resource": "" }
q5786
train
function(host, username, password) { var defaultUrl = "http://localhost:8085"; host = host || defaultUrl; if (username && password) { var protocol = host.match(/(^|\s)(https?:\/\/)/i); if (_.isArray(protocol)) { protocol = _.first(protocol);
javascript
{ "resource": "" }
q5787
checkErrorsWithResult
train
function checkErrorsWithResult(error, response) { var errors = checkErrors(error, response); if (errors !== false) { return errors; } try { var body = JSON.parse(response.body); } catch (parseError) { return parseError; }
javascript
{ "resource": "" }
q5788
checkErrors
train
function checkErrors(error, response) { if (error) { return error instanceof Error ? error : new Error(error); } // Bamboo API enable plan returns 204 with
javascript
{ "resource": "" }
q5789
mergeUrlWithParams
train
function mergeUrlWithParams(url, params) { params = params || {};
javascript
{ "resource": "" }
q5790
client
train
function client (root) { return { tasks: { // Create a new task create: function (task, done) { post(root + 'tasks', task, done); }, // Get all tasks get: function (query, done) { get(root + 'tasks', query, done); }, // Get results for all tasks results: function (query, done) { get(root + 'tasks/results', query, done); } }, task: function (id) { return { // Get a task get: function (query, done) { get(root + 'tasks/' + id, query, done); }, // Edit a task edit: function (edits, done) { patch(root + 'tasks/' + id, edits, done); }, // Remove a task remove: function (done) { del(root + 'tasks/' + id,
javascript
{ "resource": "" }
q5791
routeUrl
train
function routeUrl(location) { if (location.hash.indexOf('#/register') == 0) { var hashparts = location.hash.split('?'); var params = {}; if (hashparts.length == 2) { var pairs = hashparts[1].split('&');
javascript
{ "resource": "" }
q5792
processSlides
train
function processSlides() { var sections = document.querySelectorAll( '[data-markdown]'), section; for( var i = 0, len = sections.length; i < len; i++ ) { section = sections[i]; if( section.getAttribute( 'data-markdown' ).length ) { var xhr = new XMLHttpRequest(), url = section.getAttribute( 'data-markdown' ); datacharset = section.getAttribute( 'data-charset' ); // see https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute#Notes if( datacharset != null && datacharset != '' ) { xhr.overrideMimeType( 'text/html; charset=' + datacharset ); } xhr.onreadystatechange = function() { if( xhr.readyState === 4 ) { if ( xhr.status >= 200 && xhr.status < 300 ) { section.outerHTML = slidify( xhr.responseText, { separator: section.getAttribute( 'data-separator' ), verticalSeparator: section.getAttribute( 'data-vertical' ), notesSeparator: section.getAttribute( 'data-notes' ), attributes: getForwardedAttributes( section ) }); } else { section.outerHTML = '<section data-state="alert">' + 'ERROR: The attempt to fetch ' + url + ' failed with HTTP status ' + xhr.status + '.' + 'Check your browser\'s JavaScript console for more details.' + '<p>Remember that you need to serve the presentation HTML from a HTTP server.</p>' + '</section>'; }
javascript
{ "resource": "" }
q5793
insertAnchors
train
function insertAnchors(content) { var $ = cheerio.load(content); $(':header').each(function(i, elem) { var header = $(elem); var id = header.attr("id"); if (!id) { id = slug(header.text()); header.attr("id", id); } header.prepend('<a name="' +
javascript
{ "resource": "" }
q5794
simplecryptor
train
function simplecryptor (password, options = {}) { const db = this // set default ignore options.ignore = ['_id', '_rev', '_deleted'].concat(options.ignore) const simpleCryptoJS = new SimpleCryptoJS(password) // https://github.com/pouchdb-community/transform-pouch#example-encryption db.transform({ incoming: function (doc) {
javascript
{ "resource": "" }
q5795
mergeToMap
train
function mergeToMap(arrFileObj) { return arrFileObj.reduce(function(result, fileObj) { var name; var libData;
javascript
{ "resource": "" }
q5796
createActionType
train
function createActionType(prefix, stage, separator) { if (typeof prefix !== 'string' || typeof stage !== 'string') { throw new
javascript
{ "resource": "" }
q5797
toFixedWidth
train
function toFixedWidth(value, maxChars) { var result = value.toFixed(2).substr(0, maxChars); if (result[result.length - 1] == '.') {
javascript
{ "resource": "" }
q5798
_getPushContext
train
function _getPushContext(context) { var pushContext; if (context && typeof context.push === "function") { // `context` is an `Assert` context pushContext = context; } else if (context && context.assert && typeof context.assert.push === "function") { // `context` is a `Test` context pushContext = context.assert; } else if ( QUnit && QUnit.config && QUnit.config.current && QUnit.config.current.assert && typeof QUnit.config.current.assert.push === "function" ) { // `context` is an unknown context but we can find the `Assert` context via QUnit
javascript
{ "resource": "" }
q5799
shouldSkip
train
function shouldSkip(file, rough) { // Basically, if rough, any small change should still process the content return rough
javascript
{ "resource": "" }