_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q10700
populate
train
function populate(schemas) { var resolver = new Resolver(schemas); // Reduce force sequential execution. return Promise.reduce(resolver.resolve(), populateSchema.bind(this), []); }
javascript
{ "resource": "" }
q10701
populateSchema
train
function populateSchema(result, schema) { var knex = this.knex; return knex.schema.hasTable(schema.tableName) .then(function (exists) { if (! exists || ! schema.populate) return result; return schema.populate(knex) .then(function () { return result.concat([schema]); }); }); }
javascript
{ "resource": "" }
q10702
train
function () { var oGrid = this.dom.grid; var iWidth = $(oGrid.wrapper).width(); var iBodyHeight = $(this.s.dt.nTable.parentNode).outerHeight(); var iFullHeight = $(this.s.dt.nTable.parentNode.parentNode).outerHeight(); var oOverflow = this._fnDTOverflow(); var iLeftWidth = this.s.iLeftWidth, iRightWidth = this.s.iRightWidth, iRight; var scrollbarAdjust = function ( node, width ) { if ( ! oOverflow.bar ) { // If there is no scrollbar (Macs) we need to hide the auto scrollbar node.style.width = (width+20)+"px"; node.style.paddingRight = "20px"; node.style.boxSizing = "border-box"; } else { // Otherwise just overflow by the scrollbar node.style.width = (width+oOverflow.bar)+"px"; } }; // When x scrolling - don't paint the fixed columns over the x scrollbar if ( oOverflow.x ) { iBodyHeight -= oOverflow.bar; } oGrid.wrapper.style.height = iFullHeight+"px"; if ( this.s.iLeftColumns > 0 ) { oGrid.left.wrapper.style.width = iLeftWidth+"px"; oGrid.left.wrapper.style.height = "1px"; oGrid.left.body.style.height = iBodyHeight+"px"; if ( oGrid.left.foot ) { oGrid.left.foot.style.top = (oOverflow.x ? oOverflow.bar : 0)+"px"; // shift footer for scrollbar } scrollbarAdjust( oGrid.left.liner, iLeftWidth ); oGrid.left.liner.style.height = iBodyHeight+"px"; } if ( this.s.iRightColumns > 0 ) { iRight = iWidth - iRightWidth; if ( oOverflow.y ) { iRight -= oOverflow.bar; } oGrid.right.wrapper.style.width = iRightWidth+"px"; oGrid.right.wrapper.style.left = iRight+"px"; oGrid.right.wrapper.style.height = "1px"; oGrid.right.body.style.height = iBodyHeight+"px"; if ( oGrid.right.foot ) { oGrid.right.foot.style.top = (oOverflow.x ? oOverflow.bar : 0)+"px"; } scrollbarAdjust( oGrid.right.liner, iRightWidth ); oGrid.right.liner.style.height = iBodyHeight+"px"; oGrid.right.headBlock.style.display = oOverflow.y ? 'block' : 'none'; oGrid.right.footBlock.style.display = oOverflow.y ? 'block' : 'none'; } }
javascript
{ "resource": "" }
q10703
train
function () { var nTable = this.s.dt.nTable; var nTableScrollBody = nTable.parentNode; var out = { "x": false, "y": false, "bar": this.s.dt.oScroll.iBarWidth }; if ( nTable.offsetWidth > nTableScrollBody.clientWidth ) { out.x = true; } if ( nTable.offsetHeight > nTableScrollBody.clientHeight ) { out.y = true; } return out; }
javascript
{ "resource": "" }
q10704
train
function ( bAll ) { this._fnGridLayout(); this._fnCloneLeft( bAll ); this._fnCloneRight( bAll ); /* Draw callback function */ if ( this.s.fnDrawCallback !== null ) { this.s.fnDrawCallback.call( this, this.dom.clone.left, this.dom.clone.right ); } /* Event triggering */ $(this).trigger( 'draw.dtfc', { "leftClone": this.dom.clone.left, "rightClone": this.dom.clone.right } ); }
javascript
{ "resource": "" }
q10705
train
function ( bAll ) { if ( this.s.iRightColumns <= 0 ) { return; } var that = this, i, jq, aiColumns = []; for ( i=this.s.iTableColumns-this.s.iRightColumns ; i<this.s.iTableColumns ; i++ ) { if ( this.s.dt.aoColumns[i].bVisible ) { aiColumns.push( i ); } } this._fnClone( this.dom.clone.right, this.dom.grid.right, aiColumns, bAll ); }
javascript
{ "resource": "" }
q10706
train
function ( bAll ) { if ( this.s.iLeftColumns <= 0 ) { return; } var that = this, i, jq, aiColumns = []; for ( i=0 ; i<this.s.iLeftColumns ; i++ ) { if ( this.s.dt.aoColumns[i].bVisible ) { aiColumns.push( i ); } } this._fnClone( this.dom.clone.left, this.dom.grid.left, aiColumns, bAll ); }
javascript
{ "resource": "" }
q10707
train
function ( aoOriginal, aiColumns ) { var aReturn = []; var aClones = []; var aCloned = []; for ( var i=0, iLen=aoOriginal.length ; i<iLen ; i++ ) { var aRow = []; aRow.nTr = $(aoOriginal[i].nTr).clone(true, true)[0]; for ( var j=0, jLen=this.s.iTableColumns ; j<jLen ; j++ ) { if ( $.inArray( j, aiColumns ) === -1 ) { continue; } var iCloned = $.inArray( aoOriginal[i][j].cell, aCloned ); if ( iCloned === -1 ) { var nClone = $(aoOriginal[i][j].cell).clone(true, true)[0]; aClones.push( nClone ); aCloned.push( aoOriginal[i][j].cell ); aRow.push( { "cell": nClone, "unique": aoOriginal[i][j].unique } ); } else { aRow.push( { "cell": aClones[ iCloned ], "unique": aoOriginal[i][j].unique } ); } } aReturn.push( aRow ); } return aReturn; }
javascript
{ "resource": "" }
q10708
train
function ( nodeName, original, clone ) { if ( this.s.sHeightMatch == 'none' && nodeName !== 'thead' && nodeName !== 'tfoot' ) { return; } var that = this, i, iLen, iHeight, iHeight2, iHeightOriginal, iHeightClone, rootOriginal = original.getElementsByTagName(nodeName)[0], rootClone = clone.getElementsByTagName(nodeName)[0], jqBoxHack = $('>'+nodeName+'>tr:eq(0)', original).children(':first'), iBoxHack = jqBoxHack.outerHeight() - jqBoxHack.height(), anOriginal = this._fnGetTrNodes( rootOriginal ), anClone = this._fnGetTrNodes( rootClone ), heights = []; for ( i=0, iLen=anClone.length ; i<iLen ; i++ ) { iHeightOriginal = anOriginal[i].offsetHeight; iHeightClone = anClone[i].offsetHeight; iHeight = iHeightClone > iHeightOriginal ? iHeightClone : iHeightOriginal; if ( this.s.sHeightMatch == 'semiauto' ) { anOriginal[i]._DTTC_iHeight = iHeight; } heights.push( iHeight ); } for ( i=0, iLen=anClone.length ; i<iLen ; i++ ) { anClone[i].style.height = heights[i]+"px"; anOriginal[i].style.height = heights[i]+"px"; } }
javascript
{ "resource": "" }
q10709
train
function(r, g, b, a) { var rgb = [r, g, b].map(function (c) { return number(c); }); a = number(a); if (rgb.some(isNaN) || isNaN(a)) return null; rgb.push(a); return rgb; }
javascript
{ "resource": "" }
q10710
train
function(h, s, l, a) { h = (number(h) % 360) / 360; s = number(s); l = number(l); a = number(a); if ([h, s, l, a].some(isNaN)) return null; var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s, m1 = l * 2 - m2; return this.rgba(hue(h + 1 / 3) * 255, hue(h) * 255, hue(h - 1 / 3) * 255, a); function hue(h) { h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h); if (h * 6 < 1) return m1 + (m2 - m1) * h * 6; else if (h * 2 < 1) return m2; else if (h * 3 < 2) return m1 + (m2 - m1) * (2 / 3 - h) * 6; else return m1; } }
javascript
{ "resource": "" }
q10711
train
function(color, amount) { var hsl = this.toHSL(color); hsl.s += amount / 100; hsl.s = clamp(hsl.s); return hsla(hsl); }
javascript
{ "resource": "" }
q10712
train
function(color, amount) { var hsl = this.toHSL(color); hsl.l += amount / 100; hsl.l = clamp(hsl.l); return hsla(hsl); }
javascript
{ "resource": "" }
q10713
train
function(color1, color2, amount) { var p = amount / 100.0; var w = p * 2 - 1; var hsl1 = this.toHSL(color1); var hsl2 = this.toHSL(color2); var a = hsl1.a - hsl2.a; var w1 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0; var w2 = 1 - w1; var rgb = [ color1[0] * w1 + color2[0] * w2, color1[1] * w1 + color2[1] * w2, color1[2] * w1 + color2[2] * w2 ]; var alpha = color1[3] * p + color2[3] * (1 - p); rgb[3] = alpha; return rgb; }
javascript
{ "resource": "" }
q10714
reportResult
train
function reportResult(devRes, scriptRes, method) { debug('in performRetry', devRes, scriptRes, method); var returnData = { 'numAttempts': context.currentAttempt, 'maxAttempts': context.maxAttempts, // 'startTime': new Date(), // 'finishTime': new Date(), 'scriptRes': scriptRes, 'evalStr': context.evalStr, 'delay': context.delay, 'register': context.register, }; var devResKeys = Object.keys(devRes); devResKeys.forEach(function(key) { returnData[key] = devRes[key]; }); valChecker.defered[method](returnData); }
javascript
{ "resource": "" }
q10715
performRetry
train
function performRetry(devRes, scriptRes) { var currentAttempt = context.currentAttempt; var maxAttempts = context.maxAttempts; var delay = context.delay; debug('in performRetry', currentAttempt, maxAttempts, delay); if(currentAttempt < maxAttempts) { context.currentAttempt += 1; setTimeout(checkDeviceValue, delay); } else { if(context.rejectOnError) { reportResult(devRes, scriptRes, 'reject'); } else { reportResult(devRes, scriptRes, 'resolve'); } } }
javascript
{ "resource": "" }
q10716
urlMatch
train
function urlMatch (asset, pattern) { var multi = pattern.split(',') var re if (multi.length > 1) { for (var i = 0, len = multi.length; i < len; i++) { re = new RegExp(multi[i].replace(/([.?+^$[\]\\(){}|/-])/g, '\\$1').replace(/\*/g, '.*')) if (re.test(asset)) { return true } } return false } re = new RegExp(pattern.replace(/([.?+^$[\]\\(){}|/-])/g, '\\$1').replace(/\*/g, '.*')) return re.test(asset) }
javascript
{ "resource": "" }
q10717
isDuplicate
train
function isDuplicate (assetToCheck, isHost) { if (parsedAssets.length <= 0) { return false } return ~parsedAssets.findIndex(function (asset) { if (isHost) { // We don't want to preconnect twice, eh? return asset.split('//')[1] === assetToCheck.split('//')[1] } return asset === assetToCheck }) }
javascript
{ "resource": "" }
q10718
logger
train
function logger (message, warn) { if (appOptions.silent) { return } if (warn) { console.warn(message) return } console.log(message) }
javascript
{ "resource": "" }
q10719
hasInsertionPoint
train
function hasInsertionPoint (file) { var token = appOptions.pageToken if (token !== '' && String(file.contents).indexOf(token) > -1) { insertionPoint = 'token' return true } else if (token !== '' && token !== defaults.pageToken) { logger('Token not found in ' + file.relative) } var soup = new Soup(String(file.contents)) // Append after metas soup.setInnerHTML('head > meta:last-of-type', function (oldHTML) { if (oldHTML !== null) { insertionPoint = 'meta' return oldHTML } }) if (insertionPoint) { return true } // Else, prepend before links soup.setInnerHTML('head > link:first-of-type', function (oldHTML) { if (oldHTML !== null) { insertionPoint = 'link' return oldHTML } }) if (insertionPoint) { return true } // Else, append to head soup.setInnerHTML('head', function (oldHTML) { if (oldHTML !== null) { insertionPoint = 'head' return oldHTML } }) return insertionPoint }
javascript
{ "resource": "" }
q10720
buildResourceHint
train
function buildResourceHint (hint, asset, glob) { var as = '' if (hint === 'dns-prefetch' || hint === 'preconnect') { if (!urlMatch(asset, glob)) { return '' } asset = urlParse(asset) if (isDuplicate(asset, true)) { return '' } } else { if (!minimatch(asset, glob) || isDuplicate(asset)) { return '' } if (globMatch(asset, fonts)) { as += ' as="font"' } else if (isCSS(asset)) { as += ' as="style"' } } parsedAssets.push(asset) return `<link rel="${hint}" href="${asset}"${as} />` }
javascript
{ "resource": "" }
q10721
options
train
function options (userOpts) { if (appLoaded && typeof userOpts === 'undefined') { return appOptions } userOpts = typeof userOpts === 'object' ? userOpts : {} appOptions = Object.assign({}, defaults, userOpts) appOptions.paths = Object.assign({}, defaults.paths, userOpts.paths) appLoaded = true return appOptions }
javascript
{ "resource": "" }
q10722
writeDataToFile
train
function writeDataToFile (file, data, token) { // insertionPoint was set in hasInsertionPoint(), so we can assume it is safe to write to file var selectors = [ 'head > meta:last-of-type', 'head > link:first-of-type', 'head' ] var selectorIndex = 0 switch (insertionPoint) { case 'meta': selectorIndex = 0 break case 'link': selectorIndex = 1 break case 'head': selectorIndex = 2 break case 'token': let html = String(file.contents).replace(token, data) return new Buffer(html) default: return '' } var soup = new Soup(String(file.contents)) // Inject Resource Hints soup.setInnerHTML(selectors[selectorIndex], function (oldHTML) { if (insertionPoint === 'link') { return data + oldHTML } return oldHTML + data }) return soup.toString() }
javascript
{ "resource": "" }
q10723
train
function() { this.numTrainingExamples = 0; this.groupFrequencyCount = new Object(); this.numWords = 0; this.wordFrequencyCount = new Object(); this.groupWordTotal = new Object(); this.groupWordFrequencyCount = new Object(); }
javascript
{ "resource": "" }
q10724
incrementOrCreateGroup
train
function incrementOrCreateGroup(object, group, value) { if(!object[group]) object[group] = new Object(); var myGroup = object[group]; if(myGroup[value]) myGroup[value] += 1; else myGroup[value] = 1; }
javascript
{ "resource": "" }
q10725
isValid
train
function isValid(app) { if (isValidApp(app, 'base-helpers', ['app', 'views', 'collection'])) { debug('initializing <%s>, from <%s>', __filename, module.parent.id); return true; } return false; }
javascript
{ "resource": "" }
q10726
repeat
train
function repeat(ch, count) { var s = ''; for(var i = 0; i < count; i++) s += ch; return s; }
javascript
{ "resource": "" }
q10727
fitWidth
train
function fitWidth(s, len) { s = s.trim(); if(s.length <= len) return [s]; var result = []; while(s.length > len) { var i = len for(; s[i] != ' ' && i >= 0; i--) /* empty loop */ ; if(i == -1) { for(i = len + 1; s[i] != ' ' && i < s.length; i++) /* empty loop */ ; if(i == s.length) { result.push(s); return result; } } result.push(s.substr(0, i)); s = s.substr(i).trimLeft(); } result.push(s); return result; }
javascript
{ "resource": "" }
q10728
forEach
train
function forEach(obj, cb, ctx) { for(var key in obj) cb.call(ctx, key, obj[key]); }
javascript
{ "resource": "" }
q10729
map
train
function map(obj, cb, ctx) { var result = {}; forEach(obj, function(key, val){ result[key] = cb.call(ctx, key, val); }, ctx); return result; }
javascript
{ "resource": "" }
q10730
unique
train
function unique(list) { return Object.keys(list.reduce((obj, key) => { if (!hasProp.call(obj, key)) { obj[key] = true; } return obj; }, {})); }
javascript
{ "resource": "" }
q10731
find
train
function find(list, predicate) { // eslint-disable-line consistent-return for (var i = 0, length = list.length, item; i < length; i++) { item = list[i]; if (predicate(item)) { return item; } } }
javascript
{ "resource": "" }
q10732
setSortingLevels
train
function setSortingLevels(packages, type) { function setLevel(initial, pkg) { var level = Math.max(pkg.sortingLevel || 0, initial); var deps = Object.keys(pkg.dependencies); // console.log('setLevel', pkg.name, level); pkg.sortingLevel = level; deps.forEach(depName => { depName = sanitizeRepo(depName); var dep = find(packages, _ => { if (type === "component") { var repo = _[dependencyLocator[type]]; if (repo === depName) { return true; } // nasty hack to ensure component repo ends with the specified repo // e.g. "repo": "https://raw.github.com/component/typeof" var suffix = "/" + depName; return repo.indexOf(suffix, repo.length - suffix.length) !== -1; } return _[dependencyLocator[type]] === depName; }); if (!dep) { var names = Object.keys(packages).map(_ => { return packages[_].name; }).join(", "); throw new Error("Dependency \"" + depName + "\" is not present in the list of deps [" + names + "]. Specify correct dependency in " + type + ".json or contact package author."); } setLevel(initial + 1, dep); }); } packages.forEach(setLevel.bind(null, 1)); return packages; }
javascript
{ "resource": "" }
q10733
sortPackages
train
function sortPackages(packages, type) { return setSortingLevels(packages, type).sort((a, b) => { return b.sortingLevel - a.sortingLevel; }); }
javascript
{ "resource": "" }
q10734
createStore
train
function createStore(ClonedVue, rawModules, state) { let Vuex = require('vuex'); if (typeof Vuex.default !== 'undefined') { Vuex = Vuex.default; } ClonedVue.use(Vuex); // create a normalized copy of our vuex modules const normalizedModules = normalizeModules(rawModules); // merge in any test specific state const modules = mergeTestState(normalizedModules, state); // return the instantiated vuex store return new Vuex.Store({ state, modules, strict: true }); }
javascript
{ "resource": "" }
q10735
mungeNonPixel
train
function mungeNonPixel( elem, value ) { // IE8 and has percent value if ( window.getComputedStyle || value.indexOf('%') === -1 ) { return value; } var style = elem.style; // Remember the original values var left = style.left; var rs = elem.runtimeStyle; var rsLeft = rs && rs.left; // Put in the new values to get a computed value out if ( rsLeft ) { rs.left = elem.currentStyle.left; } style.left = value; value = style.pixelLeft; // Revert the changed values style.left = left; if ( rsLeft ) { rs.left = rsLeft; } return value; }
javascript
{ "resource": "" }
q10736
onReady
train
function onReady( event ) { // bail if already triggered or IE8 document is not ready just yet var isIE8NotReady = event.type === 'readystatechange' && document.readyState !== 'complete'; if ( docReady.isReady || isIE8NotReady ) { return; } trigger(); }
javascript
{ "resource": "" }
q10737
query
train
function query( elem, selector ) { // append to fragment if no parent checkParent( elem ); // match elem with all selected elems of parent var elems = elem.parentNode.querySelectorAll( selector ); for ( var i=0, len = elems.length; i < len; i++ ) { // return true if match if ( elems[i] === elem ) { return true; } } // otherwise return false return false; }
javascript
{ "resource": "" }
q10738
train
function (notation) { var tokens = this.notationRe.exec(notation); this.rolls = tokens[1] === undefined ? this.defaultRolls : parseInt(tokens[1]); // default if omitted this.sides = tokens[2] === undefined ? this.defaultSides : parseInt(tokens[2]); // default if omitted var after = tokens[3]; var additionTokens; if (after) { // we have third part of notation if (after === '-L') { this.specials.chooseLowest = true; } else if (after === '-H') { this.specials.chooseHighest = true; } else { additionTokens = this.additionRe.exec(after); this.specials.add = parseInt(additionTokens[2]); if (additionTokens[1] === '-') { this.specials.add *= -1; } } } return this; }
javascript
{ "resource": "" }
q10739
train
function( oDTSettings, oInit ) { /* Santiy check that we are a new instance */ if ( !this.CLASS || this.CLASS != "ColVis" ) { alert( "Warning: ColVis must be initialised with the keyword 'new'" ); } if ( typeof oInit == 'undefined' ) { oInit = {}; } var camelToHungarian = $.fn.dataTable.camelToHungarian; if ( camelToHungarian ) { camelToHungarian( ColVis.defaults, ColVis.defaults, true ); camelToHungarian( ColVis.defaults, oInit ); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public class variables * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * @namespace Settings object which contains customisable information for * ColVis instance. Augmented by ColVis.defaults */ this.s = { /** * DataTables settings object * @property dt * @type Object * @default null */ "dt": null, /** * Customisation object * @property oInit * @type Object * @default passed in */ "oInit": oInit, /** * Flag to say if the collection is hidden * @property hidden * @type boolean * @default true */ "hidden": true, /** * Store the original visibility settings so they could be restored * @property abOriginal * @type Array * @default [] */ "abOriginal": [] }; /** * @namespace Common and useful DOM elements for the class instance */ this.dom = { /** * Wrapper for the button - given back to DataTables as the node to insert * @property wrapper * @type Node * @default null */ "wrapper": null, /** * Activation button * @property button * @type Node * @default null */ "button": null, /** * Collection list node * @property collection * @type Node * @default null */ "collection": null, /** * Background node used for shading the display and event capturing * @property background * @type Node * @default null */ "background": null, /** * Element to position over the activation button to catch mouse events when using mouseover * @property catcher * @type Node * @default null */ "catcher": null, /** * List of button elements * @property buttons * @type Array * @default [] */ "buttons": [], /** * List of group button elements * @property groupButtons * @type Array * @default [] */ "groupButtons": [], /** * Restore button * @property restore * @type Node * @default null */ "restore": null }; /* Store global reference */ ColVis.aInstances.push( this ); /* Constructor logic */ this.s.dt = $.fn.dataTable.Api ? new $.fn.dataTable.Api( oDTSettings ).settings()[0] : oDTSettings; this._fnConstruct( oInit ); return this; }
javascript
{ "resource": "" }
q10740
train
function ( init ) { $.extend( true, this.s, ColVis.defaults, init ); // Slightly messy overlap for the camelCase notation if ( ! this.s.showAll && this.s.bShowAll ) { this.s.showAll = this.s.sShowAll; } if ( ! this.s.restore && this.s.bRestore ) { this.s.restore = this.s.sRestore; } // CamelCase to Hungarian for the column groups var groups = this.s.groups; var hungarianGroups = this.s.aoGroups; if ( groups ) { for ( var i=0, ien=groups.length ; i<ien ; i++ ) { if ( groups[i].title ) { hungarianGroups[i].sTitle = groups[i].title; } if ( groups[i].columns ) { hungarianGroups[i].aiColumns = groups[i].columns; } } } }
javascript
{ "resource": "" }
q10741
train
function () { var columns = this.s.dt.aoColumns; var buttons = this.dom.buttons; var groups = this.s.aoGroups; var button; for ( var i=0, ien=buttons.length ; i<ien ; i++ ) { button = buttons[i]; if ( button.__columnIdx !== undefined ) { $('input', button).prop( 'checked', columns[ button.__columnIdx ].bVisible ); } } var allVisible = function ( columnIndeces ) { for ( var k=0, kLen=columnIndeces.length ; k<kLen ; k++ ) { if ( columns[columnIndeces[k]].bVisible === false ) { return false; } } return true; }; var allHidden = function ( columnIndeces ) { for ( var m=0 , mLen=columnIndeces.length ; m<mLen ; m++ ) { if ( columns[columnIndeces[m]].bVisible === true ) { return false; } } return true; }; for ( var j=0, jLen=groups.length ; j<jLen ; j++ ) { if ( allVisible(groups[j].aiColumns) ) { $('input', this.dom.groupButtons[j]).prop('checked', true); $('input', this.dom.groupButtons[j]).prop('indeterminate', false); } else if ( allHidden(groups[j].aiColumns) ) { $('input', this.dom.groupButtons[j]).prop('checked', false); $('input', this.dom.groupButtons[j]).prop('indeterminate', false); } else { $('input', this.dom.groupButtons[j]).prop('indeterminate', true); } } }
javascript
{ "resource": "" }
q10742
train
function () { var nButton, columns = this.s.dt.aoColumns; if ( $.inArray( 'all', this.s.aiExclude ) === -1 ) { for ( var i=0, iLen=columns.length ; i<iLen ; i++ ) { if ( $.inArray( i, this.s.aiExclude ) === -1 ) { nButton = this._fnDomColumnButton( i ); nButton.__columnIdx = i; this.dom.buttons.push( nButton ); } } } if ( this.s.order === 'alpha' ) { this.dom.buttons.sort( function ( a, b ) { var titleA = columns[ a.__columnIdx ].sTitle; var titleB = columns[ b.__columnIdx ].sTitle; return titleA === titleB ? 0 : titleA < titleB ? -1 : 1; } ); } if ( this.s.restore ) { nButton = this._fnDomRestoreButton(); nButton.className += " ColVis_Restore"; this.dom.buttons.push( nButton ); } if ( this.s.showAll ) { nButton = this._fnDomShowXButton( this.s.showAll, true ); nButton.className += " ColVis_ShowAll"; this.dom.buttons.push( nButton ); } if ( this.s.showNone ) { nButton = this._fnDomShowXButton( this.s.showNone, false ); nButton.className += " ColVis_ShowNone"; this.dom.buttons.push( nButton ); } $(this.dom.collection).append( this.dom.buttons ); }
javascript
{ "resource": "" }
q10743
train
function () { var that = this, dt = this.s.dt; return $( '<li class="ColVis_Special '+(dt.bJUI ? 'ui-button ui-state-default' : '')+'">'+ this.s.restore+ '</li>' ) .click( function (e) { for ( var i=0, iLen=that.s.abOriginal.length ; i<iLen ; i++ ) { that.s.dt.oInstance.fnSetColumnVis( i, that.s.abOriginal[i], false ); } that._fnAdjustOpenRows(); that.s.dt.oInstance.fnAdjustColumnSizing( false ); that.s.dt.oInstance.fnDraw( false ); } )[0]; }
javascript
{ "resource": "" }
q10744
train
function () { for ( var i=0, iLen=this.s.dt.oInstance.length ; i<iLen ; i++ ) { if ( this.s.dt.oInstance[i] == this.s.dt.nTable ) { return i; } } return 0; }
javascript
{ "resource": "" }
q10745
train
function () { var that = this, nCatcher = document.createElement('div'); nCatcher.className = "ColVis_catcher"; $(nCatcher).click( function () { that._fnCollectionHide.call( that, null, null ); } ); return nCatcher; }
javascript
{ "resource": "" }
q10746
train
function () { var aoOpen = this.s.dt.aoOpenRows; var iVisible = this.s.dt.oApi._fnVisbleColumns( this.s.dt ); for ( var i=0, iLen=aoOpen.length ; i<iLen ; i++ ) { aoOpen[i].nTr.getElementsByTagName('td')[0].colSpan = iVisible; } }
javascript
{ "resource": "" }
q10747
train
function(match, value, len, step) { var num = '' + value; if (doubled(match, step)) { while (num.length < len) { num = '0' + num; } } return num; }
javascript
{ "resource": "" }
q10748
train
function(match, value, shortNames, longNames) { return (doubled(match) ? longNames[value] : shortNames[value]); }
javascript
{ "resource": "" }
q10749
train
function(date, useLongName) { if (useLongName) { return (typeof monthNames === 'function') ? monthNames.call(calendar, date) : monthNames[date.month() - calendar.minMonth]; } else { return (typeof monthNamesShort === 'function') ? monthNamesShort.call(calendar, date) : monthNamesShort[date.month() - calendar.minMonth]; } }
javascript
{ "resource": "" }
q10750
train
function(match, step) { var isDoubled = doubled(match, step); var size = [2, 3, isDoubled ? 4 : 2, isDoubled ? 4 : 2, 10, 11, 20]['oyYJ@!'.indexOf(match) + 1]; var digits = new RegExp('^-?\\d{1,' + size + '}'); var num = value.substring(iValue).match(digits); if (!num) { throw ($.calendars.local.missingNumberAt || $.calendars.regionalOptions[''].missingNumberAt). replace(/\{0\}/, iValue); } iValue += num[0].length; return parseInt(num[0], 10); }
javascript
{ "resource": "" }
q10751
train
function() { if (typeof monthNames === 'function') { var month = doubled('M') ? monthNames.call(calendar, value.substring(iValue)) : monthNamesShort.call(calendar, value.substring(iValue)); iValue += month.length; return month; } return getName('M', monthNamesShort, monthNames); }
javascript
{ "resource": "" }
q10752
wrap
train
function wrap(fn, args, key) { const self = this; if (key === undefined && typeof(args) === 'string') { key = args; args = []; } if (!args) args = []; return function wrapper(context, cb) { const copyArgs = args.slice(args); copyArgs.unshift(self); copyArgs.push(onWrappedDone); return fn.bind.apply(fn, copyArgs)(); function onWrappedDone(err, result) { if (err) return cb(err); if (key) context[key] = result; return cb(null); } }; }
javascript
{ "resource": "" }
q10753
each
train
function each(items, numParralel, fn, done) { if (done === undefined) { done = fn; fn = numParralel; numParralel = 3; } if (numParralel <= 0) numParralel = 1; let doing = 0; let numProcessing = 0; let numDone = 0; const numTotal = items.length; const results = []; return nextItem(); function nextItem() { // We done-check first in case of emtpty array if (numDone >= numTotal) return done(null, results); // Batch (or call next item) while (doing < numTotal && numProcessing < numParralel) { callFn(fn, items[doing++], onDone); numProcessing++; } return; // All done function onDone(err, result) { if (err) return done(err); results.push(result); numProcessing--; numDone++; return nextItem(); } } }
javascript
{ "resource": "" }
q10754
make
train
function make() { // create a map of all flow functions wrapped by _make const makeFnMap = {}; Object.keys(fnMap).forEach(function (key) { makeFnMap[key] = _make(fnMap[key]); }); return makeFnMap; // takes a function and wraps it so that execution is 'postponed' function _make(fn) { // the user calls this function, e.g. flw.make.series(...) return function madeFunction(fns, context, returnKey) { if (typeof context === 'string') { returnKey = context; context = {}; } // this function is consumed by flw return function flowFunction(context, cb) { // when passed from a flw flow it's called with a premade context // if called directly, create a new context if (cb === undefined && typeof context === 'function') { cb = context; context = {}; _checkContext(context); } if (typeof cb !== 'function') { throw new Error('flw: .make - cb !== function'); } return fn(fns, context, returnKey, cb); }; }; } }
javascript
{ "resource": "" }
q10755
_make
train
function _make(fn) { // the user calls this function, e.g. flw.make.series(...) return function madeFunction(fns, context, returnKey) { if (typeof context === 'string') { returnKey = context; context = {}; } // this function is consumed by flw return function flowFunction(context, cb) { // when passed from a flw flow it's called with a premade context // if called directly, create a new context if (cb === undefined && typeof context === 'function') { cb = context; context = {}; _checkContext(context); } if (typeof cb !== 'function') { throw new Error('flw: .make - cb !== function'); } return fn(fns, context, returnKey, cb); }; }; }
javascript
{ "resource": "" }
q10756
_checkContext
train
function _checkContext(c) { if (c.hasOwnProperty('_stopped')) return; // Already done? c._stopped = null; // Indicate that we gracefully stop // if set, stops the flow until we are back to the main callback function _flw_stop(reason, cb) { if (!cb && typeof reason === 'function') { cb = reason; reason = 'stopped'; } c._stopped = reason; return cb(); } Object.defineProperty(c, '_stop', { enumerable: false, configurable: false, writable: false, value: _flw_stop, }); // Stores the data returned from the callback in the context with key 'key' // then calls the callback function _flw_store(key, cb) { const self = this; const fn = function (err, data) { if (err) return cb(err); self[key] = data; return cb(); }; return fn; } Object.defineProperty(c, '_store', { enumerable: false, configurable: false, value: _flw_store, }); // Cleans all flw related properties from the context object function _flw_clean() { const self = this; const contextCopy = {}; Object.keys(this).forEach(function (k) { if (ourContextKeys.indexOf(k) !== -1) return; contextCopy[k] = self[k]; }); return contextCopy; } Object.defineProperty(c, '_clean', { enumerable: false, configurable: false, value: _flw_clean, }); // compatibilty for a while Object.defineProperty(c, '_flw_store', { enumerable: false, configurable: false, writable: false, value: _flw_store, }); return c; }
javascript
{ "resource": "" }
q10757
_flw_stop
train
function _flw_stop(reason, cb) { if (!cb && typeof reason === 'function') { cb = reason; reason = 'stopped'; } c._stopped = reason; return cb(); }
javascript
{ "resource": "" }
q10758
_flw_store
train
function _flw_store(key, cb) { const self = this; const fn = function (err, data) { if (err) return cb(err); self[key] = data; return cb(); }; return fn; }
javascript
{ "resource": "" }
q10759
_flw_clean
train
function _flw_clean() { const self = this; const contextCopy = {}; Object.keys(this).forEach(function (k) { if (ourContextKeys.indexOf(k) !== -1) return; contextCopy[k] = self[k]; }); return contextCopy; }
javascript
{ "resource": "" }
q10760
getNullLogger
train
function getNullLogger() { return new Proxy( {}, { get: function(target, propKey) { // not proxy for Timer if (propKey === 'Timer') { return _.bind(InnerTimer, {}, undefined) } return function() {} }, apply: function(target, object, args) {} } ) }
javascript
{ "resource": "" }
q10761
getModuleCode
train
function getModuleCode(mocks) { var filename = path.join(__dirname, './mock-angular.js'); var code = fs.readFileSync(filename, 'utf8'); return code.replace(/angular\.noop\(\);/, getModuleConfig(mocks)); }
javascript
{ "resource": "" }
q10762
getModuleConfig
train
function getModuleConfig(mocks) { // Functions cannot be transferred directly // Convert to string for (var i = 0; i < mocks.length; ++i) { var mock = mocks[i]; if (typeof mock[0] === 'function') { mock[0] = mock[0].toString(); } } return "angular.module('vinkaga.mockBackend').constant('vinkaga.mockBackend.mock', " + JSON.stringify(mocks) + ');'; }
javascript
{ "resource": "" }
q10763
rollup
train
function rollup(imbuff) { var roll = new Buffer(0); Object.keys(imbuff).sort().forEach(function(id){ roll = crypto.createHash('sha256').update(Buffer.concat([roll,new Buffer(id, 'hex')])).digest(); roll = crypto.createHash('sha256').update(Buffer.concat([roll,imbuff[id]])).digest(); }); return roll; }
javascript
{ "resource": "" }
q10764
connectStore
train
function connectStore(component, keys) { var shouldReturnAFunction = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; // function that maps store state to component props var mapStateToProps = function mapStateToProps(state) { // initialize return object var mappedState = {}; // populate return object keys.forEach(function (key) { // add selector connection if (key.split(':').length === 2 && selectors[key.split(':')[1]]) { mappedState[key.split(':')[0]] = selectors[key.split(':')[1]](state); // add branch connection } else if (state[key]) { mappedState[key] = state[key].toJS(); } }); return shouldReturnAFunction ? function (state, props) { return mappedState; } : mappedState; }; return (0, _reactRedux.connect)(mapStateToProps)(component); }
javascript
{ "resource": "" }
q10765
mapStateToProps
train
function mapStateToProps(state) { // initialize return object var mappedState = {}; // populate return object keys.forEach(function (key) { // add selector connection if (key.split(':').length === 2 && selectors[key.split(':')[1]]) { mappedState[key.split(':')[0]] = selectors[key.split(':')[1]](state); // add branch connection } else if (state[key]) { mappedState[key] = state[key].toJS(); } }); return shouldReturnAFunction ? function (state, props) { return mappedState; } : mappedState; }
javascript
{ "resource": "" }
q10766
applyTransform
train
function applyTransform(data, headers, status, fns) { if (typeof fns === 'function') { data = fns(data, headers, status); } else { for (var i = 0; i < fns.length; i++) { data = fns[i](data, headers, status); } } return data; }
javascript
{ "resource": "" }
q10767
isMatch
train
function isMatch(config, mock) { if (angular.isFunction(mock)) { return !!mock(config.method, config.url, config.params, config.data, config.headers); } mock = mock || {}; var fail = false; if (mock.method) { fail = fail || (config.method ? config.method.toLowerCase() : 'get') != mock.method.toLowerCase(); } if (mock.url && angular.isString(config.url) && angular.isString(mock.url)) { fail = fail || config.url.split('?')[0] != mock.url.split('?')[0]; } if (mock.params || angular.isString(config.url) && config.url.split('?')[1]) { var configParams = angular.extend(queryParams(config.url.split('?')[1]), config.params); var mockParams = angular.isString(mock.url) ? queryParams(mock.url.split('?')[1]) : {}; mockParams = angular.extend(mockParams, mock.params); fail = fail || !angular.equals(configParams, mockParams); } if (mock.data) { fail = fail || !angular.equals(config.data, mock.data); } // Header props can be functions if (mock.headers) { var headers = {}; angular.forEach(config.headers, function(value, key) { if (angular.isFunction(value)) { value = value(config); } if (value) { headers[key] = value; } }); fail = fail || !angular.equals(headers, mock.headers); } return !fail; }
javascript
{ "resource": "" }
q10768
applyRequestInterceptors
train
function applyRequestInterceptors(config) { for (var i = 0; i < interceptors.length; i++) { var interceptor = getInterceptor(interceptors[i]); if (interceptor.request) { config = interceptor.request(config); } } if (config.transformRequest) { config.data = applyTransform(config.data, config.headers, undefined, config.transformRequest); } return config; }
javascript
{ "resource": "" }
q10769
applyResponseInterceptors
train
function applyResponseInterceptors(response) { if (response.config.transformResponse) { response.data = applyTransform(response.data, response.headers, response.status, response.config.transformResponse); } for (var i = interceptors.length - 1; i >= 0; i--) { var interceptor = getInterceptor(interceptors[i]); if (interceptor.response) { response = interceptor.response(response); } } return response; }
javascript
{ "resource": "" }
q10770
getMock
train
function getMock(config) { for (var i = 0; i < mocks.length; i++) { if (isMatch(config, mocks[i].config)) { return mocks[i]; } } return undefined; }
javascript
{ "resource": "" }
q10771
delay
train
function delay(mock, response) { if (!mock || !mock.delay) { return response; } return $q(function(resolve, reject) { setTimeout(function() { resolve(response); }, mock.delay); }); }
javascript
{ "resource": "" }
q10772
responsePromise
train
function responsePromise(response) { response.status = response.status || 200; return $q(function(resolve, reject) { (response.status >= 200 && response.status <= 299 ? resolve : reject)(response); }); }
javascript
{ "resource": "" }
q10773
makeIter
train
function makeIter(iterable) { if (typeof iterable[iterSymbol] === 'function') { // passed argument can create iterators - create new one. return iterable[iterSymbol](); } if (!_isSubscriptable(iterable)) { throw Error('Unsupported argument type'); } // passed argument can be indexed, eg. string, array, etc. // - create new iter object. var idx = -1; return { next: function() { return ++idx < iterable.length ? {done: false, value: iterable[idx]} : {done: true}; } }; }
javascript
{ "resource": "" }
q10774
toArray
train
function toArray(iterable) { // kinda optimisations if (isArray(iterable)) { return iterable.slice(); } if (typeof iterable === 'string') { return iterable.split(''); } var iter = ensureIter(iterable); var result = []; var next = iter.next(); while (!next.done) { result.push(next.value); next = iter.next(); } return result; }
javascript
{ "resource": "" }
q10775
getOBAuth
train
function getOBAuth(config) { // debugger; // Encoding as per API Specification. const combinedCredential = `${config.clientId}:${config.clientSecret}`; // var base64Credential = window.btoa(combinedCredential); const base64Credential = Buffer.from(combinedCredential).toString("base64"); const readyCredential = `Basic ${base64Credential}`; return readyCredential; }
javascript
{ "resource": "" }
q10776
getNotifications
train
async function getNotifications(config) { try { const options = { method: "GET", uri: `${config.obServer}:${config.obPort}/ob/notifications`, json: true, // Automatically stringifies the body to JSON headers: { Authorization: config.apiCredentials, }, // resolveWithFullResponse: true }; return rp(options); } catch (err) { console.error(`Error in openbazaar.js/getNotifications(): ${err}`); console.error(`Error stringified: ${JSON.stringify(err, null, 2)}`); throw err; } }
javascript
{ "resource": "" }
q10777
createListing
train
function createListing(config, listingData) { const options = { method: "POST", uri: `${config.obServer}:${config.obPort}/ob/listing/`, body: listingData, json: true, // Automatically stringifies the body to JSON headers: { Authorization: config.apiCredentials, }, }; return rp(options); }
javascript
{ "resource": "" }
q10778
createProfile
train
function createProfile(config, profileData) { const options = { method: "POST", uri: `${config.obServer}:${config.obPort}/ob/profile/`, body: profileData, json: true, // Automatically stringifies the body to JSON headers: { Authorization: config.apiCredentials, }, // resolveWithFullResponse: true }; return rp(options); }
javascript
{ "resource": "" }
q10779
getExchangeRate
train
function getExchangeRate(config) { const options = { method: "GET", uri: `${config.obServer}:${config.obPort}/ob/exchangerate`, json: true, // Automatically stringifies the body to JSON headers: { Authorization: config.apiCredentials, }, // resolveWithFullResponse: true }; return rp(options); }
javascript
{ "resource": "" }
q10780
cut
train
function cut(c, i) { var a = adj[i][c[i]] a.splice(a.indexOf(c), 1) }
javascript
{ "resource": "" }
q10781
next
train
function next(a, b, noCut) { var nextCell, nextVertex, nextDir for(var i=0; i<2; ++i) { if(adj[i][b].length > 0) { nextCell = adj[i][b][0] nextDir = i break } } nextVertex = nextCell[nextDir^1] for(var dir=0; dir<2; ++dir) { var nbhd = adj[dir][b] for(var k=0; k<nbhd.length; ++k) { var e = nbhd[k] var p = e[dir^1] var cmp = compareAngle( positions[a], positions[b], positions[nextVertex], positions[p]) if(cmp > 0) { nextCell = e nextVertex = p nextDir = dir } } } if(noCut) { return nextVertex } if(nextCell) { cut(nextCell, nextDir) } return nextVertex }
javascript
{ "resource": "" }
q10782
handlerFor
train
function handlerFor( scope ) { const { axVisibility } = widgetServices( scope ); axVisibility.onChange( updateState ); scope.$on( '$destroy', () => { axVisibility.unsubscribe( updateState ); } ); let lastState = axVisibility.isVisible(); /** * A scope bound visibility handler. * * @name axVisibilityServiceHandler */ const api = { /** * Determine if the governing widget scope's DOM is visible right now. * * @return {Boolean} * `true` if the widget associated with this handler is visible right now, else `false` * * @memberOf axVisibilityServiceHandler */ isVisible() { return axVisibility.isVisible(); }, ////////////////////////////////////////////////////////////////////////////////////////////////// /** * Schedule a handler to be called with the new DOM visibility on any DOM visibility change. * * @param {Function<Boolean>} handler * the callback to process visibility changes * * @return {axVisibilityServiceHandler} * this visibility handler (for chaining) * * @memberOf axVisibilityServiceHandler */ onChange( handler ) { addHandler( handler, true ); addHandler( handler, false ); return api; }, ////////////////////////////////////////////////////////////////////////////////////////////////// /** * Schedule a handler to be called with the new DOM visibility when it has changed to `true`. * * @param {Function<Boolean>} handler * the callback to process visibility changes * * @return {axVisibilityServiceHandler} * this visibility handler (for chaining) * * @memberOf axVisibilityServiceHandler */ onShow( handler ) { addHandler( handler, true ); return api; }, ////////////////////////////////////////////////////////////////////////////////////////////////// /** * Schedule a handler to be called with the new DOM visibility when it has changed to `false`. * * @param {Function<Boolean>} handler * the callback to process visibility changes * * @return {axVisibilityServiceHandler} * this visibility handler (for chaining) * * @memberOf axVisibilityServiceHandler */ onHide( handler ) { addHandler( handler, false ); return api; }, ////////////////////////////////////////////////////////////////////////////////////////////////// /** * Removes all visibility handlers. * * @return {axVisibilityServiceHandler} * this visibility handler (for chaining) * * @memberOf axVisibilityServiceHandler */ clear }; const showHandlers = []; const hideHandlers = []; return api; ///////////////////////////////////////////////////////////////////////////////////////////////////// function clear() { showHandlers.splice( 0, showHandlers.length ); hideHandlers.splice( 0, hideHandlers.length ); return api; } ///////////////////////////////////////////////////////////////////////////////////////////////////// // eslint-disable-next-line valid-jsdoc /** * Run all handlers registered for the given area and target state after the next heartbeat. * Also remove any handlers that have been cleared since the last run. * @private */ function updateState( targetState ) { const state = axVisibility.isVisible(); if( state === lastState ) { return; } lastState = state; heartbeat.onAfterNext( () => { const handlers = targetState ? showHandlers : hideHandlers; handlers.forEach( f => f( targetState ) ); } ); } ///////////////////////////////////////////////////////////////////////////////////////////////////// // eslint-disable-next-line valid-jsdoc /** * Add a show/hide-handler for a given area and visibility state. Execute the handler right away if * the state is already known, and `true` (since all widgets start as invisible). * @private */ function addHandler( handler, targetState ) { ( targetState ? showHandlers : hideHandlers ).push( handler ); // State already known to be true? In that case, initialize: if( targetState && axVisibility.isVisible() === targetState ) { handler( targetState ); } } }
javascript
{ "resource": "" }
q10783
updateState
train
function updateState( targetState ) { const state = axVisibility.isVisible(); if( state === lastState ) { return; } lastState = state; heartbeat.onAfterNext( () => { const handlers = targetState ? showHandlers : hideHandlers; handlers.forEach( f => f( targetState ) ); } ); }
javascript
{ "resource": "" }
q10784
train
function( oDT, oConfig ) { /* Sanity check that we are a new instance */ if ( ! (this instanceof AutoFill) ) { throw( "Warning: AutoFill must be initialised with the keyword 'new'" ); } if ( ! $.fn.dataTableExt.fnVersionCheck('1.7.0') ) { throw( "Warning: AutoFill requires DataTables 1.7 or greater"); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public class variables * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ this.c = {}; /** * @namespace Settings object which contains customisable information for AutoFill instance */ this.s = { /** * @namespace Cached information about the little dragging icon (the filler) */ "filler": { "height": 0, "width": 0 }, /** * @namespace Cached information about the border display */ "border": { "width": 2 }, /** * @namespace Store for live information for the current drag */ "drag": { "startX": -1, "startY": -1, "startTd": null, "endTd": null, "dragging": false }, /** * @namespace Data cache for information that we need for scrolling the screen when we near * the edges */ "screen": { "interval": null, "y": 0, "height": 0, "scrollTop": 0 }, /** * @namespace Data cache for the position of the DataTables scrolling element (when scrolling * is enabled) */ "scroller": { "top": 0, "bottom": 0 }, /** * @namespace Information stored for each column. An array of objects */ "columns": [] }; /** * @namespace Common and useful DOM elements for the class instance */ this.dom = { "table": null, "filler": null, "borderTop": null, "borderRight": null, "borderBottom": null, "borderLeft": null, "currentTarget": null }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public class methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Retreieve the settings object from an instance * @method fnSettings * @returns {object} AutoFill settings object */ this.fnSettings = function () { return this.s; }; /* Constructor logic */ this._fnInit( oDT, oConfig ); return this; }
javascript
{ "resource": "" }
q10785
train
function ( nTd ) { var nTr = $(nTd).parents('tr')[0]; var position = this.s.dt.oInstance.fnGetPosition( nTd ); return { "x": $('td', nTr).index(nTd), "y": $('tr', nTr.parentNode).index(nTr), "row": position[0], "column": position[2] }; }
javascript
{ "resource": "" }
q10786
train
function (e) { if ( e.target && e.target.nodeName.toUpperCase() == "TD" && e.target != this.s.drag.endTd ) { var coords = this._fnTargetCoords( e.target ); if ( this.c.mode == "y" && coords.x != this.s.drag.startX ) { e.target = $('tbody>tr:eq('+coords.y+')>td:eq('+this.s.drag.startX+')', this.dom.table)[0]; } if ( this.c.mode == "x" && coords.y != this.s.drag.startY ) { e.target = $('tbody>tr:eq('+this.s.drag.startY+')>td:eq('+coords.x+')', this.dom.table)[0]; } if ( this.c.mode == "either") { if(coords.x != this.s.drag.startX ) { e.target = $('tbody>tr:eq('+this.s.drag.startY+')>td:eq('+coords.x+')', this.dom.table)[0]; } else if ( coords.y != this.s.drag.startY ) { e.target = $('tbody>tr:eq('+coords.y+')>td:eq('+this.s.drag.startX+')', this.dom.table)[0]; } } // update coords if ( this.c.mode !== "both" ) { coords = this._fnTargetCoords( e.target ); } var drag = this.s.drag; drag.endTd = e.target; if ( coords.y >= this.s.drag.startY ) { this._fnUpdateBorder( drag.startTd, drag.endTd ); } else { this._fnUpdateBorder( drag.endTd, drag.startTd ); } this._fnFillerPosition( e.target ); } /* Update the screen information so we can perform scrolling */ this.s.screen.y = e.pageY; this.s.screen.scrollTop = $(document).scrollTop(); if ( this.s.dt.oScroll.sY !== "" ) { this.s.scroller.scrollTop = $(this.s.dt.nTable.parentNode).scrollTop(); this.s.scroller.top = $(this.s.dt.nTable.parentNode).offset().top; this.s.scroller.bottom = this.s.scroller.top + $(this.s.dt.nTable.parentNode).height(); } }
javascript
{ "resource": "" }
q10787
train
function (e) { var filler = this.dom.filler; /* Don't display automatically when dragging */ if ( this.s.drag.dragging) { return; } /* Check that we are allowed to AutoFill this column or not */ var nTd = (e.target.nodeName.toLowerCase() == 'td') ? e.target : $(e.target).parents('td')[0]; var iX = this._fnTargetCoords(nTd).column; if ( !this.s.columns[iX].enable ) { filler.style.display = "none"; return; } if (e.type == 'mouseover') { this.dom.currentTarget = nTd; this._fnFillerPosition( nTd ); filler.style.display = "block"; } else if ( !e.relatedTarget || !e.relatedTarget.className.match(/AutoFill/) ) { filler.style.display = "none"; } }
javascript
{ "resource": "" }
q10788
train
function ( nTd ) { var offset = $(nTd).offset(); var filler = this.dom.filler; filler.style.top = (offset.top - (this.s.filler.height / 2)-1 + $(nTd).outerHeight())+"px"; filler.style.left = (offset.left - (this.s.filler.width / 2)-1 + $(nTd).outerWidth())+"px"; }
javascript
{ "resource": "" }
q10789
train
function ( cell, val ) { var table = $(cell).parents('table'); if ( DataTable.Api ) { // 1.10 table.DataTable().cell( cell ).data( val ); } else { // 1.9 var dt = table.dataTable(); var pos = dt.fnGetPosition( cell ); dt.fnUpdate( val, pos[0], pos[2], false ); } }
javascript
{ "resource": "" }
q10790
train
function ( cell, read, last, i, x, y ) { // Increment a number if it is found var re = /(\-?\d+)/; var match = this.increment && last ? last.match(re) : null; if ( match ) { return last.replace( re, parseInt(match[1],10) + (x<0 || y<0 ? -1 : 1) ); } return last === undefined ? read : last; }
javascript
{ "resource": "" }
q10791
fulfillName
train
function fulfillName (name, ext, mask, lang) { var shortname; var params; // support hash with params as first function param if (isPlainObject(name)) { params = name; name = params.name; ext = params.ext; mask = params.mask; lang = params.lang; } shortname = basename(name); if (mask) { name = join(name, unmaskName(shortname, mask, lang)); } var curext = extname(name); if (curext) { return name; } // prepend dot to extension if (ext[0] !== '.') { ext = '.' + ext; } return join(name, shortname + ext); }
javascript
{ "resource": "" }
q10792
unmaskName
train
function unmaskName (name, mask, lang) { return mask .replace(/\?/g, name) .replace(/\{lang\}/g, lang); }
javascript
{ "resource": "" }
q10793
createReaddirBundle
train
function createReaddirBundle(options) { return { 'changeDir': false, 'pathProvided': options.pathProvided, 'path': options.path, 'readdirPath': options.path, 'cwd': '', 'startingDir': '', 'fileNames': [], 'files': [], 'noFilesOnCard': false, 'isError': false, 'errorStep': '', 'error': undefined, 'errorCode': 0, }; }
javascript
{ "resource": "" }
q10794
forEachFilename
train
function forEachFilename( files, callback ) { files.forEach( function ( file ) { file.src.forEach( function ( src ) { if ( ! grunt.file.exists( src ) ) { grunt.verbose.writeln( 'source file "' + src + '" not found' ); return false; } if ( grunt.file.isDir( src ) ) { grunt.verbose.writeln( 'source file "' + src + '" seems to be a directory' ); return false; } var filename = path.relative( file.orig.cwd, src ); callback( src, filename, file.dest, file.orig.cwd ); }); }); }
javascript
{ "resource": "" }
q10795
password
train
function password(req, res, test) { var options = { grant_type: "password", client_id: process.env.SALESFORCE_CLIENT_ID, client_secret: process.env.SALESFORCE_CLIENT_SECRET, username: req.query.username || req.body.username || process.env.SALESFORCE_USERNAME, password: req.query.password || req.body.password || process.env.SALESFORCE_PASSWORD, } var protocol = "https://"; if(test === true || req.test) protocol = "http://"; //for testing var loginServer = req.body.login_server || req.query.login_server || "login.salesforce.com"; var url = protocol + loginServer + "/services/oauth2/token"; var r = request.post(url) .type("application/x-www-form-urlencoded") .send(options) .on("error", function(err){ return onError(res, err); }) .end(function(sfRes){ if(sfRes.error) return onError(res, sfRes.error + " " + JSON.stringify(sfRes.body) ); req.session.salesforce = JSON.stringify( sfRes.body ); if (process.env.NODE_ENV === 'development') router.session = req.session.salesforce; res.redirect( req.query.app_url || process.env.SALESFORCE_FINAL_URL || "/login/whoami" ) }) }
javascript
{ "resource": "" }
q10796
login
train
function login(req, res, test) { var protocol = "https://"; if(test === true || req.test) protocol = "http://"; //for testing var loginServer = req.query.login_server || "login.salesforce.com"; var url = protocol + loginServer + "/services/oauth2/authorize"; var state = JSON.stringify({ loginServer: loginServer, appUrl: req.query.app_url || process.env.SALESFORCE_FINAL_URL || "/login/whoami", profile: req.query.profile }); var options = { response_type: "code", client_id: process.env.SALESFORCE_CLIENT_ID, redirect_uri: process.env.SALESFORCE_REDIRECT_URL, state: state } return res.redirect(url + "?" + querystring.stringify(options) ); }
javascript
{ "resource": "" }
q10797
loginCallback
train
function loginCallback(req, res, test) { var state = JSON.parse(req.query.state); console.dir( state ); var protocol = "https://"; if(test === true || req.test) protocol = "http://"; //for testing var url = protocol + state.loginServer + "/services/oauth2/token"; var options = { code: req.query.code, grant_type: 'authorization_code', client_id: process.env.SALESFORCE_CLIENT_ID, redirect_uri: process.env.SALESFORCE_REDIRECT_URL, client_secret: process.env.SALESFORCE_CLIENT_SECRET } request.post(url) .type("application/x-www-form-urlencoded") .send(options) .on("error", function(err){ return onError(res,err); }) .end(function(sfRes){ if(sfRes.error) return onError(res, sfRes.error); console.dir( sfRes.body ) req.session.salesforce = JSON.stringify( sfRes.body ); res.redirect(state.appUrl) }) }
javascript
{ "resource": "" }
q10798
toElem
train
function toElem(shapes, callback) { var typeofShape; var txt = null; var k = 0; for (var i = 0; i < shapes.length; i++) { typeofShape = shapes[i].type; if (typeofShape == "text") { txt = shapes[i].txt; delete shapes[i].txt; } if (shapes[i].class) { shapes[i].className = shapes[i].class; delete shapes[i].class; } delete shapes[i].type; shapes[i].key = shapes[i].key || k++; if (callback) shapes[i].onClick = callback.bind(null, shapes[i].key); // Replace this by null for React shapes[i] = React.createElement(typeofShape, shapes[i], txt); } return shapes; }
javascript
{ "resource": "" }
q10799
unEquip
train
function unEquip (attributes, slotName) { if (!(slotName in attributes.equipped)) { throw new SlotNameError(slotName); } if (attributes.equipped[slotName]) { attributes.inventory.push(attributes.equipped[slotName]); } attributes.equipped[slotName] = null; return attributes; }
javascript
{ "resource": "" }