_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q12700
createTemplateWithInnerHTML
train
function createTemplateWithInnerHTML(innerHTML) { const template = document.createElement('template'); // REVIEW: Is there an easier way to do this? // We'd like to just set innerHTML on the template content, but since it's // a DocumentFragment, that doesn't work. const div = document.createElement('div'); div.innerHTML = innerHTML; while (div.childNodes.length > 0) { template.content.appendChild(div.childNodes[0]); } return template; }
javascript
{ "resource": "" }
q12701
shimTemplateStyles
train
function shimTemplateStyles(template, tag) { window.WebComponents.ShadowCSS.shimStyling(template.content, tag); }
javascript
{ "resource": "" }
q12702
compatMaxage
train
function compatMaxage(opts) { if (opts) { opts.maxage = opts.maxage === undefined ? opts.maxAge : opts.maxage; delete opts.maxAge; } }
javascript
{ "resource": "" }
q12703
render_stack_trace
train
function render_stack_trace(error, { markup_settings, log }) { // Supports custom `html` for an error if (error.html) { return { response_status: error.status, response_body: error.html } } // Handle `superagent` errors // https://github.com/visionmedia/superagent/blob/29ca1fc938b974c6623d9040a044e39dfb272fed/lib/node/response.js#L106 if (error.response && typeof error.status === 'number') { // If the `superagent` http request returned an HTML response // (possibly an error stack trace), // then just output that stack trace. if (error.response.headers['content-type'] && error.response.headers['content-type'].split(';')[0].trim() === 'text/html') { return { response_status: error.status, response_body: error.message } } } // If this error has a stack trace then it can be shown let stack_trace if (error.stack) { stack_trace = error.stack } // `superagent` errors have the `original` property // for storing the initial error else if (error.original && error.original.stack) { stack_trace = error.original.stack } // If this error doesn't have a stack trace - do nothing if (!stack_trace) { return {} } // Render the error's stack trace as HTML markup try { return { response_body: html_stack_trace({ stack: stack_trace }, markup_settings) } } catch (error) { log.error(error) // If error stack trace couldn't be rendered as HTML markup, // then just output it as plain text. return { response_body: error.stack } } }
javascript
{ "resource": "" }
q12704
Id
train
function Id(bracket, round, match) { if (!(this instanceof Id)) { return new Id(bracket, round, match); } this.s = bracket; this.r = round; this.m = match; }
javascript
{ "resource": "" }
q12705
train
function (size, p, last, isLong) { var matches = []; // first WB round to initialize players for (var i = 1; i <= Math.pow(2, p - 1); i += 1) { matches.push({ id: gId(WB, 1, i), p: woMark(seeds(i, p), size) }); } // blank WB rounds var r, g; for (r = 2; r <= p; r += 1) { for (g = 1; g <= Math.pow(2, p - r); g += 1) { matches.push({id: gId(WB, r, g), p: blank() }); } } // blank LB rounds if (last >= LB) { for (r = 1; r <= 2*p - 2; r += 1) { // number of matches halves every odd round in losers bracket for (g = 1; g <= Math.pow(2, p - 1 - Math.floor((r + 1) / 2)); g += 1) { matches.push({ id: gId(LB, r, g), p: blank() }); } } matches.push({ id: gId(LB, 2*p - 1, 1), p: blank() }); // grand final match 1 } if (isLong) { // bronze final if last === WB, else grand final match 2 matches.push({ id: gId(LB, last === LB ? 2*p : 1, 1), p: blank() }); } return matches.sort(Base.compareMatches); // sort so they can be scored in order }
javascript
{ "resource": "" }
q12706
train
function (p, round, game) { // we know round <= p var numGames = Math.pow(2, p - round); var midPoint = Math.floor(Math.pow(2, p - round - 1)); // midPoint 0 in finals // reverse the match list map var reversed = $.odd(Math.floor(round/2)); // split the match list map in two change order and rejoin the lists var partitioned = $.even(Math.floor((round + 1)/2)); if (partitioned) { if (reversed) { return (game > midPoint) ? numGames - game + midPoint + 1 : midPoint - game + 1; } return (game > midPoint) ? game - midPoint : game + midPoint; } return reversed ? numGames - game + 1 : game; }
javascript
{ "resource": "" }
q12707
train
function (id) { var b = id.s , r = id.r , g = id.m , p = this.p; // knockouts / special finals if (b >= this.last) { // greater than case is for BF in long single elimination if (b === WB && this.isLong && r === p - 1) { // if bronze final, move loser to "LBR1" at mirror pos of WBGF return [gId(LB, 1, 1), (g + 1) % 2]; } if (b === LB && r === 2*p - 1 && this.isLong) { // if double final, then loser moves to the bottom return [gId(LB, 2 * p, 1), 1]; } // otherwise always KO'd if loosing in >= last bracket return null; } // WBR1 always feeds into LBR1 as if it were WBR2 if (r === 1) { return [gId(LB, 1, Math.floor((g+1)/2)), g % 2]; } if (this.downMix) { // always drop on top when downmixing return [gId(LB, (r-1)*2, mixLbGames(p, r, g)), 0]; } // normal LB drops: on top for (r>2) and (r<=2 if odd g) to match bracket movement var pos = (r > 2 || $.odd(g)) ? 0 : 1; return [gId(LB, (r-1)*2, g), pos]; }
javascript
{ "resource": "" }
q12708
train
function (progressFn, m) { var idx = m.p.indexOf(WO); if (idx >= 0) { // set scores manually to avoid the `_verify` walkover scoring restriction m.m = (idx === 0) ? [0, 1] : [1, 0]; progressFn(m); } }
javascript
{ "resource": "" }
q12709
refresh
train
function refresh(element) { const url = window.location.href; let match; if (element.areaLink) { // Match prefix let prefix = element.href; // If prefix doesn't end in slash, add a slash. // We want to avoid matching in the middle of a folder name. if (prefix.length < url.length && prefix.substr(-1) !== '/') { prefix += '/'; } match = (url.substr(0, prefix.length) === prefix); } else { // Match whole path match = (url === element.href); } element.current = match; }
javascript
{ "resource": "" }
q12710
selectIndex
train
function selectIndex(element, index) { const count = element.items.length; const boundedIndex = (element.selectionWraps) ? // JavaScript mod doesn't handle negative numbers the way we want to wrap. // See http://stackoverflow.com/a/18618250/76472 ((index % count) + count) % count : // Keep index within bounds of array. Math.max(Math.min(index, count - 1), 0); const previousIndex = element.selectedIndex; if (previousIndex !== boundedIndex) { element.selectedIndex = boundedIndex; return true; } else { return false; } }
javascript
{ "resource": "" }
q12711
trackSelectedItem
train
function trackSelectedItem(element) { const items = element.items; const itemCount = items ? items.length : 0; const previousSelectedItem = element.selectedItem; if (!previousSelectedItem) { // No item was previously selected. if (element.selectionRequired) { // Select the first item by default. element.selectedIndex = 0; } } else if (itemCount === 0) { // We've lost the selection, and there's nothing left to select. element.selectedItem = null; } else { // Try to find the previously-selected item in the current set of items. const indexInCurrentItems = Array.prototype.indexOf.call(items, previousSelectedItem); const previousSelectedIndex = element.selectedIndex; if (indexInCurrentItems < 0) { // Previously-selected item was removed from the items. // Select the item at the same index (if it exists) or as close as possible. const newSelectedIndex = Math.min(previousSelectedIndex, itemCount - 1); // Select by item, since index may be the same, and we want to raise the // selected-item-changed event. element.selectedItem = items[newSelectedIndex]; } else if (indexInCurrentItems !== previousSelectedIndex) { // Previously-selected item still there, but changed position. element.selectedIndex = indexInCurrentItems; } } }
javascript
{ "resource": "" }
q12712
loadCompleteOptionsCmd
train
function loadCompleteOptionsCmd(options) { if(!options || typeof options !== 'object') throw new Error('expected options object') if(!options.getOptions) options = new BasicOptions(options) return options.file ? new CompositeOptions([new MultiOptions(options.file), options]) : options }
javascript
{ "resource": "" }
q12713
HttpsConfig
train
function HttpsConfig(options) { var httpsOptions = options && options.httpsOptions underscore.extend(this, HttpsConfig._DEFAULT) CommonConfig.call(this, options) this.httpsOptions = applyHttpsOptions.call(this, httpsOptions) this.type = serverTypes.HTTPS }
javascript
{ "resource": "" }
q12714
getEnvironment
train
function getEnvironment (options) { var env; if (options.environment) { env = options.environment; } else { env = process.env.NODE_ENV; } if (env) { if (env === 'prod') { env = 'production'; } else if (env === 'dev') { env = 'development'; } } else { // Default to "development" env = 'development'; } return env; }
javascript
{ "resource": "" }
q12715
loadSources
train
async function loadSources (sources, options) { const mergedConfig = {}; function handleSourceLoad (sourceConfig) { if (sourceConfig) merge(sourceConfig, mergedConfig); } for (const source of sources) { let sourceConfig; if (source == null) { // No-op... skip this source continue; } else if (typeof source === 'string') { // Load a source from a JSON file sourceConfig = await loadFileSource(source, options); } else if (Array.isArray(source)) { sourceConfig = await loadSources(source, options); // Load and merge all of the sources } else if (typeof source === 'function') { sourceConfig = await source(); // Invoke the function to asynchronously load the config object for this source } else if (typeof source === 'object') { sourceConfig = source; // Just merge the object } else { throw new Error('Invalid configuration source: ' + source); } handleSourceLoad(sourceConfig); } return mergedConfig; }
javascript
{ "resource": "" }
q12716
HttpConfig
train
function HttpConfig(options) { underscore.extend(this, HttpConfig._DEFAULT) CommonConfig.call(this, options) this.type = serverTypes.HTTP }
javascript
{ "resource": "" }
q12717
Babelify
train
function Babelify(filename, babelConfig) { stream.Transform.call(this); this._data = ''; this._filename = filename; this._babelConfig = babelConfig; }
javascript
{ "resource": "" }
q12718
buildServerCmd
train
function buildServerCmd(config) { var deferred = Q.defer() , app try { assertConfig(config) app = createMiddleware(config) createServer(config, app).then(onServerCreated, deferred.reject) } catch(error) { deferred.reject(error) } return deferred.promise function onServerCreated(server) { deferred.resolve(new Server(config, server, app)) } }
javascript
{ "resource": "" }
q12719
startServerCmd
train
function startServerCmd(options) { var deferred = Q.defer() var config try { options = loadOptions(options) config = buildConfigFromOptions(options) buildServer(config).then(onServerBuilt, onServerBuildFailed) } catch(error) { deferred.reject(error) } return deferred.promise function onServerBuilt(server) { server.start().then(deferred.resolve, onServerStartFailed) } function onServerBuildFailed(error) { var msg = (error && error.message) || 'of no good reason' console.error('failed to build server because ' + msg) deferred.reject(error) } function onServerStartFailed(error) { var msg = (error && error.message) || 'of no good reason' console.error('failed to start server becaue ' + msg) deferred.reject(error) } }
javascript
{ "resource": "" }
q12720
_makeQuery
train
function _makeQuery(conditions, fields) { // build up 'Where' string var query = fields.reduce(function(condition, field) { var addition = ''; var val = conditions[field]; var isNumber = typeof val === 'number'; if (val) { addition += field; if (isNumber) { addition += '='; } else { addition += ' like \''; } addition += val; if (!isNumber) { addition += '\''; } addition += ' and '; } return condition + addition; }, 'Where '); // remove final 'and' query = query.replace(/ and $/, ''); return new nodeGoogleDfp.Statement(query); }
javascript
{ "resource": "" }
q12721
_lookupKeyInPair
train
function _lookupKeyInPair(pair) { var key = pair[0]; var value = pair[1]; return Bluebird.all([ this.lookupCriteriaKey(key), value ]); }
javascript
{ "resource": "" }
q12722
_lookupValueInPair
train
function _lookupValueInPair(pair) { var keyId = pair[0]; var value = pair[1]; return Bluebird.all([ keyId, this.lookupCriteriaValues(value, keyId) ]); }
javascript
{ "resource": "" }
q12723
_convertPairToObject
train
function _convertPairToObject(pair) { var keyId = pair[0]; var valueIds = pair[1]; return { keyId: keyId, valueIds: valueIds }; }
javascript
{ "resource": "" }
q12724
validate
train
function validate(doc, schema, prefix, options) { schema.validate(doc, prefix, options); }
javascript
{ "resource": "" }
q12725
defaults
train
function defaults(options) { options = options || {}; return { reqHeader: options.reqHeader || 'X-Request-Id', resHeader: options.resHeader || 'X-Request-Id', paramName: options.paramName || 'requestId', generator: options.generator || uuid }; }
javascript
{ "resource": "" }
q12726
parseDecorator
train
function parseDecorator (fn) { return function (pitch) { var p = asArray(pitch) return p ? fn(p) : null } }
javascript
{ "resource": "" }
q12727
str
train
function str (pitch) { var p = Array.isArray(pitch) ? pitch : asPitch.parse(pitch) return p ? asPitch.stringify(p) : null }
javascript
{ "resource": "" }
q12728
fromMidi
train
function fromMidi (midi) { var name = CHROMATIC[midi % 12] var oct = Math.floor(midi / 12) - 1 return name + oct }
javascript
{ "resource": "" }
q12729
fromFreq
train
function fromFreq (freq, tuning) { tuning = tuning || 440 var lineal = 12 * ((Math.log(freq) - Math.log(tuning)) / Math.log(2)) var midi = Math.round(69 + lineal) return fromMidi(midi) }
javascript
{ "resource": "" }
q12730
toFreq
train
function toFreq (p, tuning) { if (NUM.test(p)) return +p var midi = toMidi(asPitch.parse(p)) if (!midi) return null tuning = tuning || 440 return Math.pow(2, (midi - 69) / 12) * tuning }
javascript
{ "resource": "" }
q12731
cents
train
function cents (from, to, decimals) { var dec = decimals ? Math.pow(10, decimals) : 100 var fromFq = toFreq(from) var toFq = toFreq(to) return Math.floor(1200 * (Math.log(toFq / fromFq) * dec / Math.log(2))) / dec }
javascript
{ "resource": "" }
q12732
demo
train
function demo() { // Translate phrase w(__('Hello!')); // Comment for translator w(__('Hello!# This is comment.')); // Phrase with id w(__('Hello!#another_hello')); // Phrase with id and comment w(__('Hello!#another_hello2 Please translate this another way.')); // Phrase with # but not comment w(__('There is ## in this phrase but it is not comment.')); // This phrase will not be translated - missing in translation. w(__('Hello?')); // Escapes for placeholders w(__('This is %% percent symbol.')); // Placeholders with additional arguments w(__('My %(0)s is faster then your %(1)s!', 'SSD', 'HDD')); // Placeholders with array w(__('My %(0)s is faster then your %(1)s!', [ 'Kawasaki', 'Segway' ])); // Placeholders with object w(__('My %(0)s is faster then your %(1)s!', { 0: 'Core i7', 1: '486DX' })); // Both names and order w(__('Let\'s count in English: %s, %s, %(3)s and %s.', 'one', 'two', 'four', 'three')); // Plural forms w(__(['Inbox: %n unreaded message.', 'Inbox: %n unreaded messages.'], 1)); w(__(['Inbox: %n unreaded message.', 'Inbox: %n unreaded messages.'], 12)); w(__(['Inbox: %n unreaded message.', 'Inbox: %n unreaded messages.'], 22)); // All-in-one w(__([ '%n developer from our team uses %(0)s with %(1)s.# Comment 1', '%n developers from our team uses %(0)s with %(1)s.# Comment 2' ], 1, 'C', 'vim' )); w(__([ '%n developer from our team uses %(0)s with %(1)s.# Comment 3', '%n developers from our team uses %(0)s with %(1)s.# Comment 4' ], 3, [ 'Python', 'PyCharm' ] )); w(__([ '%n developer from our team uses %(0)s with %(1)s.# Multiline\ncomment', '%n developers from our team uses %(0)s with %(1)s.# Another\nmultiline\ncomment' ], 7, { 0: 'Node.js', 1: 'Sublime Text 2' } )); // No args - empty string w(__()); }
javascript
{ "resource": "" }
q12733
train
function() { var cellSelector = '' + '.gl-cell > .gl-vertical,' + '.gl-cell > .gl-fill,' + '.gl-cell > .gl-scrollview,' + '.gl-cell > .gl-scrollview > .gl-scrollview-content'; var $cells = document.querySelectorAll(cellSelector); var i; var $parent; var cell; var parent; for(i = 0; i < $cells.length; i++) { cell = getBoundingClientRect.call($cells[i]); $parent = $cells[i].parentNode; parent = getBoundingClientRect.call($parent); var parentDisplay; if($parent.currentStyle) { parentDisplay = $parent.currentStyle.display; } else { parentDisplay = window.getComputedStyle($parent).display; } // instead of checking for IE by user agent, check if // and the height is wrong. if(cell.height !== parent.height) { // we can't separate property read/write into separate loops, // for performance with reflows, because we need to have the // corrent dimensions set on a cell parent, once we reach a child. $cells[i].style.height = parent.height + 'px'; // some rows without dimensions set take up more space than needed. if(parentDisplay === 'table-row') { $parent.style.height = parent.height + 'px'; } } } }
javascript
{ "resource": "" }
q12734
deepCopy
train
function deepCopy(value) { let result; if (value instanceof Buffer) { // isPlainObject(buffer) returns true. return new Buffer(value); } if (isPlainObject(value) === true) { result = {}; loopKeys(value, function(_value, key) { if (_value.hasOwnProperty(key)) { result[key] = deepCopy(_value[key]); } }); return result; } if (Array.isArray(value)) { result = []; for (let i = 0, ii = value.length; i < ii; ++i) { result.push(deepCopy(value[i])); } return result; } return value; }
javascript
{ "resource": "" }
q12735
serialize
train
function serialize(obj, opts, prefix) { var str = [] , useArraySyntax = false // if there's a prefix, and this object is an array, use array syntax // i.e., `prefix[]=foo&prefix[]=bar` instead of `prefix[0]=foo&prefix[1]=bar` if (Array.isArray(obj) && prefix) { useArraySyntax = true } Object.keys(obj).forEach(function (prop) { var key, query, val = obj[prop] key = prefix ? prefix + '[' + (useArraySyntax ? '' : prop) + ']' : prop if (val === null) { if (opts.removeNull) { return } query = opts.encodeComponents ? encodeURIComponent(key) : key } else if (typeof val === 'object') { query = serialize(val, opts, key) } else { query = opts.encodeComponents ? encodeURIComponent(key) + '=' + encodeURIComponent(val) : key + '=' + val; } str.push(query) }) return str.join('&') }
javascript
{ "resource": "" }
q12736
train
function (buf) { if (!(buf instanceof Buffer) || buf.length !== Id.SIZE) throw new Error('invalid buffer'); this._buf = buf; }
javascript
{ "resource": "" }
q12737
TuyaLinkWizard
train
function TuyaLinkWizard(options) { // Set to empty object if undefined options = options ? options : {}; if (!options.email || !options.password) { throw new Error('Both email and password must be provided'); } this.email = options.email; this.password = options.password; // Set defaults this.region = options.region ? options.region : 'AZ'; this.timezone = options.timezone ? options.timezone : '-05:00'; // Don't need to check key and secret for correct format as // tuyapi/cloud already does this.api = new Cloud({key: options.apiKey, secret: options.apiSecret, region: this.region}); // Construct instance of TuyaLink this.device = new TuyaLink(); }
javascript
{ "resource": "" }
q12738
bignumToString
train
function bignumToString(bignum, base, alphabet) { // Prefer native conversion if (alphabet === "native" && base != 6) { return bignum.toString(base); } // Old-sk00l conversion var result = []; while (bignum.gt(0)) { var ord = bignum.mod(base); result.push(alphabet.charAt(ord)); bignum = bignum.div(base); } return result.reverse().join(""); }
javascript
{ "resource": "" }
q12739
train
function (sspiClient) { if (!initializeExecutionCompleted) { // You cannot user process.nextTick() here as it will block all // I/O which means initialization in native code will never get // a chance to run and the process will just hang. setImmediate(invokeGetNextBlob, sspiClient); } else if (!initializeSucceeded) { cb(null, null, initializeErrorCode, initializeErrorString); } else { sspiClient.sspiClientImpl.getNextBlob(serverResponse, serverResponseBeginOffset, serverResponseLength, // Cannot use => function syntax here as that does not have the 'arguments'. function() { sspiClient.getNextBlobInProgress = false; cb.apply(null, arguments); }); } }
javascript
{ "resource": "" }
q12740
MockRpc
train
function MockRpc(endpoint) { events.EventEmitter.call(this); this._endpoint = endpoint; this._handlers = {}; glNetwork[endpoint] = this; }
javascript
{ "resource": "" }
q12741
getFqdnForIpAddress
train
function getFqdnForIpAddress(ipAddress, cb) { dns.reverse(ipAddress, function(err, fqdns) { if (err) { cb(err, fqdns); } else if (fqdns[0].toLowerCase() === localhostIdentifier) { getFqdn(localhostIdentifier, cb); } else { cb(err, fqdns[0]); } }); }
javascript
{ "resource": "" }
q12742
getFqdnForHostname
train
function getFqdnForHostname(hostname, cb) { let addressIndex = 0; dns.lookup(hostname, { all: true }, function (err, addresses, family) { const tryNextAddressOrComplete = (err, fqdn) => { addressIndex++; if (!err) { cb(err, fqdn); } else if (addressIndex != addresses.length) { getFqdnForIpAddress(addresses[addressIndex].address, tryNextAddressOrComplete); } else { cb(err); } }; if (!err) { getFqdnForIpAddress(addresses[addressIndex].address, tryNextAddressOrComplete); } else { cb(err); } }); }
javascript
{ "resource": "" }
q12743
train
function (localId, bucketSize) { if (!(localId instanceof Id)) throw new Error('id must be a valid identifier'); this._bucketSize = bucketSize; this._root = new Bucket(bucketSize); Object.defineProperty(this, 'id', {value: localId}); }
javascript
{ "resource": "" }
q12744
makeAsync
train
function makeAsync(cb) { return function () { var args = arguments; process.nextTick(function () { cb.apply(null, args); }); }; }
javascript
{ "resource": "" }
q12745
checkInterface
train
function checkInterface(obj, funcs) { for (var i = 0; i < funcs.length; ++i) { if (typeof obj[funcs[i]] !== 'function') return false; } return true; }
javascript
{ "resource": "" }
q12746
defaultOptions
train
function defaultOptions(opts) { opts.bucketSize = opts.bucketSize || 20; opts.concurrency = opts.concurrency || 3; opts.expireTime = opts.expireTime || 60 * 60 * 24; opts.refreshTime = opts.refreshTime || 60 * 60; opts.replicateTime = opts.replicateTime || 60 * 60; opts.republishTime = opts.republishTime || 60 * 60 * 24; }
javascript
{ "resource": "" }
q12747
LookupList
train
function LookupList(id, capacity) { if (!(id instanceof Id)) throw new Error('invalid id or selfId'); if (!(typeof capacity === 'number' && capacity > 0)) throw new Error('invalid capacity'); this._id = id; this._capacity = capacity; this._slots = []; }
javascript
{ "resource": "" }
q12748
demo
train
function demo(dht1, dht2) { dht1.set('beep', 'boop', function (err) { if (err) throw err; dht2.get('beep', function (err, value) { if (err) throw err; console.log('%s === %s', 'boop', value); }); }); }
javascript
{ "resource": "" }
q12749
ValidatorError
train
function ValidatorError (path, type) { var msg = type ? '"' + type + '" ' : ''; NeopreneError.call(this, 'Validator ' + msg + 'failed for path ' + path); Error.captureStackTrace(this, arguments.callee); this.name = 'ValidatorError'; this.path = path; this.type = type; }
javascript
{ "resource": "" }
q12750
train
function (coords) { var row; if (priv.dataType === 'array') { row = []; for (var c = 0; c < self.colCount; c++) { row.push(null); } } else { row = $.extend(true, {}, datamap.getSchema()); } if (!coords || coords.row >= self.rowCount) { priv.settings.data.push(row); } else { priv.settings.data.splice(coords.row, 0, row); } }
javascript
{ "resource": "" }
q12751
train
function (coords) { if (priv.dataType === 'object' || priv.settings.columns) { throw new Error("Cannot create new column. When data source in an object, you can only have as much columns as defined in first data row, data schema or in the 'columns' setting"); } var r = 0; if (!coords || coords.col >= self.colCount) { for (; r < self.rowCount; r++) { if (typeof priv.settings.data[r] === 'undefined') { priv.settings.data[r] = []; } priv.settings.data[r].push(''); } } else { for (; r < self.rowCount; r++) { priv.settings.data[r].splice(coords.col, 0, ''); } } }
javascript
{ "resource": "" }
q12752
train
function (coords, toCoords) { if (!coords || coords.row === self.rowCount - 1) { priv.settings.data.pop(); } else { priv.settings.data.splice(coords.row, toCoords.row - coords.row + 1); } }
javascript
{ "resource": "" }
q12753
train
function (coords, toCoords) { if (priv.dataType === 'object' || priv.settings.columns) { throw new Error("cannot remove column with object data source or columns option specified"); } var r = 0; if (!coords || coords.col === self.colCount - 1) { for (; r < self.rowCount; r++) { priv.settings.data[r].pop(); } } else { var howMany = toCoords.col - coords.col + 1; for (; r < self.rowCount; r++) { priv.settings.data[r].splice(coords.col, howMany); } } }
javascript
{ "resource": "" }
q12754
train
function (row, prop) { if (typeof prop === 'string' && prop.indexOf('.') > -1) { var sliced = prop.split("."); var out = priv.settings.data[row]; if (!out) { return null; } for (var i = 0, ilen = sliced.length; i < ilen; i++) { out = out[sliced[i]]; if (typeof out === 'undefined') { return null; } } return out; } else { return priv.settings.data[row] ? priv.settings.data[row][prop] : null; } }
javascript
{ "resource": "" }
q12755
train
function (row, prop, value) { if (typeof prop === 'string' && prop.indexOf('.') > -1) { var sliced = prop.split("."); var out = priv.settings.data[row]; for (var i = 0, ilen = sliced.length - 1; i < ilen; i++) { out = out[sliced[i]]; } out[sliced[i]] = value; } else { priv.settings.data[row][prop] = value; } }
javascript
{ "resource": "" }
q12756
train
function () { for (var r = 0; r < self.rowCount; r++) { for (var c = 0; c < self.colCount; c++) { datamap.set(r, datamap.colToProp(c), ''); } } }
javascript
{ "resource": "" }
q12757
train
function (start, end) { var r, rlen, c, clen, output = [], row; rlen = Math.max(start.row, end.row); clen = Math.max(start.col, end.col); for (r = Math.min(start.row, end.row); r <= rlen; r++) { row = []; for (c = Math.min(start.col, end.col); c <= clen; c++) { row.push(datamap.get(r, datamap.colToProp(c))); } output.push(row); } return output; }
javascript
{ "resource": "" }
q12758
train
function ($td, cellProperties) { if (priv.isPopulated) { var data = $td.data('readOnly'); if (typeof data === 'undefined') { return !cellProperties.readOnly; } else { return !data; } } return true; }
javascript
{ "resource": "" }
q12759
train
function (start, input, end, source) { var r, rlen, c, clen, td, setData = [], current = {}; rlen = input.length; if (rlen === 0) { return false; } current.row = start.row; current.col = start.col; for (r = 0; r < rlen; r++) { if ((end && current.row > end.row) || (!priv.settings.minSpareRows && current.row > self.countRows() - 1) || (current.row >= priv.settings.maxRows)) { break; } current.col = start.col; clen = input[r] ? input[r].length : 0; for (c = 0; c < clen; c++) { if ((end && current.col > end.col) || (!priv.settings.minSpareCols && current.col > self.colCount - 1) || (current.col >= priv.settings.maxCols)) { break; } td = self.view.getCellAtCoords(current); if (self.getCellMeta(current.row, current.col).isWritable) { var p = datamap.colToProp(current.col); setData.push([current.row, p, input[r][c]]); } current.col++; if (end && c === clen - 1) { c = -1; } } current.row++; if (end && r === rlen - 1) { r = -1; } } self.setDataAtCell(setData, null, null, source || 'populateFromArray'); }
javascript
{ "resource": "" }
q12760
train
function () { var tds = self.view.getAllCells(); for (var i = 0, ilen = tds.length; i < ilen; i++) { $(tds[i]).empty(); self.minWidthFix(tds[i]); } }
javascript
{ "resource": "" }
q12761
train
function (start, end) { var corners = grid.getCornerCoords([start, end]); var r, c, output = []; for (r = corners.TL.row; r <= corners.BR.row; r++) { for (c = corners.TL.col; c <= corners.BR.col; c++) { output.push(self.view.getCellAtCoords({ row: r, col: c })); } } return output; }
javascript
{ "resource": "" }
q12762
train
function (td) { selection.deselect(); priv.selStart = self.view.getCellCoords(td); selection.setRangeEnd(td); }
javascript
{ "resource": "" }
q12763
train
function (td, scrollToCell) { var coords = self.view.getCellCoords(td); selection.end(coords); if (!priv.settings.multiSelect) { priv.selStart = coords; } self.rootElement.triggerHandler("selection.handsontable", [priv.selStart.row, priv.selStart.col, priv.selEnd.row, priv.selEnd.col]); self.rootElement.triggerHandler("selectionbyprop.handsontable", [priv.selStart.row, datamap.colToProp(priv.selStart.col), priv.selEnd.row, datamap.colToProp(priv.selEnd.col)]); selection.refreshBorders(); if (scrollToCell !== false) { self.view.scrollViewport(td); } }
javascript
{ "resource": "" }
q12764
train
function (revertOriginal, keepEditor) { if (!keepEditor) { editproxy.destroy(revertOriginal); } if (!selection.isSelected()) { return; } selection.refreshBorderDimensions(); if (!keepEditor) { editproxy.prepare(); } }
javascript
{ "resource": "" }
q12765
train
function () { if (!selection.isSelected()) { return; } if (autofill.handle) { autofill.showHandle(); } priv.currentBorder.appear([priv.selStart]); highlight.on(); }
javascript
{ "resource": "" }
q12766
train
function () { return !(priv.selEnd.col === priv.selStart.col && priv.selEnd.row === priv.selStart.row); }
javascript
{ "resource": "" }
q12767
train
function (coords) { if (!selection.isSelected()) { return false; } var sel = grid.getCornerCoords([priv.selStart, priv.selEnd]); return (sel.TL.row <= coords.row && sel.BR.row >= coords.row && sel.TL.col <= coords.col && sel.BR.col >= coords.col); }
javascript
{ "resource": "" }
q12768
train
function () { if (!selection.isSelected()) { return; } highlight.off(); priv.currentBorder.disappear(); if (autofill.handle) { autofill.hideHandle(); } selection.end(false); editproxy.destroy(); self.rootElement.triggerHandler('deselect.handsontable'); }
javascript
{ "resource": "" }
q12769
train
function () { if (!priv.settings.multiSelect) { return; } var tds = self.view.getAllCells(); if (tds.length) { selection.setRangeStart(tds[0]); selection.setRangeEnd(tds[tds.length - 1], false); } }
javascript
{ "resource": "" }
q12770
train
function () { if (!selection.isSelected()) { return; } var corners = grid.getCornerCoords([priv.selStart, selection.end()]); var r, c, changes = []; for (r = corners.TL.row; r <= corners.BR.row; r++) { for (c = corners.TL.col; c <= corners.BR.col; c++) { if (self.getCellMeta(r, c).isWritable) { changes.push([r, datamap.colToProp(c), '']); } } } self.setDataAtCell(changes); }
javascript
{ "resource": "" }
q12771
train
function () { if (!selection.isSelected()) { return false; } if (selection.isMultiple()) { priv.selectionBorder.appear([priv.selStart, selection.end()]); } else { priv.selectionBorder.disappear(); } }
javascript
{ "resource": "" }
q12772
train
function () { if (!autofill.handle) { autofill.handle = new Handsontable.FillHandle(self); autofill.fillBorder = new Handsontable.Border(self, { className: 'htFillBorder' }); $(autofill.handle.handle).on('dblclick', autofill.selectAdjacent); } else { autofill.handle.disabled = false; autofill.fillBorder.disabled = false; } self.rootElement.on('beginediting.handsontable', function () { autofill.hideHandle(); }); self.rootElement.on('finishediting.handsontable', function () { if (selection.isSelected()) { autofill.showHandle(); } }); }
javascript
{ "resource": "" }
q12773
train
function () { var select, data, r, maxR, c; if (selection.isMultiple()) { select = priv.selectionBorder.corners; } else { select = priv.currentBorder.corners; } autofill.fillBorder.disappear(); data = datamap.getAll(); rows : for (r = select.BR.row + 1; r < self.rowCount; r++) { for (c = select.TL.col; c <= select.BR.col; c++) { if (data[r][c]) { break rows; } } if (!!data[r][select.TL.col - 1] || !!data[r][select.BR.col + 1]) { maxR = r; } } if (maxR) { autofill.showBorder(self.view.getCellAtCoords({row: maxR, col: select.BR.col})); autofill.apply(); } }
javascript
{ "resource": "" }
q12774
train
function () { var drag, select, start, end; autofill.handle.isDragged = 0; drag = autofill.fillBorder.corners; if (!drag) { return; } autofill.fillBorder.disappear(); if (selection.isMultiple()) { select = priv.selectionBorder.corners; } else { select = priv.currentBorder.corners; } if (drag.TL.row === select.TL.row && drag.TL.col < select.TL.col) { start = drag.TL; end = { row: drag.BR.row, col: select.TL.col - 1 }; } else if (drag.TL.row === select.TL.row && drag.BR.col > select.BR.col) { start = { row: drag.TL.row, col: select.BR.col + 1 }; end = drag.BR; } else if (drag.TL.row < select.TL.row && drag.TL.col === select.TL.col) { start = drag.TL; end = { row: select.TL.row - 1, col: drag.BR.col }; } else if (drag.BR.row > select.BR.row && drag.TL.col === select.TL.col) { start = { row: select.BR.row + 1, col: drag.TL.col }; end = drag.BR; } if (start) { grid.populateFromArray(start, SheetClip.parse(priv.editProxy.val()), end, 'autofill'); selection.setRangeStart(self.view.getCellAtCoords(drag.TL)); selection.setRangeEnd(self.view.getCellAtCoords(drag.BR)); } else { //reset to avoid some range bug selection.refreshBorders(); } }
javascript
{ "resource": "" }
q12775
train
function (td) { var coords = self.view.getCellCoords(td); var corners = grid.getCornerCoords([priv.selStart, priv.selEnd]); if (priv.settings.fillHandle !== 'horizontal' && (corners.BR.row < coords.row || corners.TL.row > coords.row)) { coords = {row: coords.row, col: corners.BR.col}; } else if (priv.settings.fillHandle !== 'vertical') { coords = {row: corners.BR.row, col: coords.col}; } else { return; //wrong direction } autofill.fillBorder.appear([priv.selStart, priv.selEnd, coords]); }
javascript
{ "resource": "" }
q12776
train
function () { priv.editProxy.height(priv.editProxy.parent().innerHeight() - 4); priv.editProxy.val(datamap.getText(priv.selStart, priv.selEnd)); setTimeout(editproxy.focus, 1); priv.editorDestroyer = self.view.applyCellTypeMethod('editor', self.view.getCellAtCoords(priv.selStart), priv.selStart, priv.editProxy); }
javascript
{ "resource": "" }
q12777
train
function (i) { var deferred = $.Deferred(); deferreds.push(deferred); var originalVal = changes[i][3]; var lowercaseVal = typeof originalVal === 'string' ? originalVal.toLowerCase() : null; return function (source) { var found = false; for (var s = 0, slen = source.length; s < slen; s++) { if (originalVal === source[s]) { found = true; //perfect match break; } else if (lowercaseVal === source[s].toLowerCase()) { changes[i][3] = source[s]; //good match, fix the case found = true; break; } } if (!found) { changes[i] = null; } deferred.resolve(); } }
javascript
{ "resource": "" }
q12778
train
function (keyboardProxy) { var el = keyboardProxy[0]; if (el.selectionStart) { return el.selectionStart; } else if (document.selection) { el.focus(); var r = document.selection.createRange(); if (r == null) { return 0; } var re = el.createTextRange(), rc = re.duplicate(); re.moveToBookmark(r.getBookmark()); rc.setEndPoint('EndToStart', re); return rc.text.length; } return 0; }
javascript
{ "resource": "" }
q12779
train
function (keyboardProxy, pos) { var el = keyboardProxy[0]; if (el.setSelectionRange) { el.focus(); el.setSelectionRange(pos, pos); } else if (el.createTextRange) { var range = el.createTextRange(); range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } }
javascript
{ "resource": "" }
q12780
train
function (instance, td, row, col, prop, keyboardProxy, useOriginalValue, suffix) { if (texteditor.isCellEdited) { return; } keyboardProxy.on('cut.editor', function (event) { event.stopPropagation(); }); keyboardProxy.on('paste.editor', function (event) { event.stopPropagation(); }); var $td = $(td); if (!instance.getCellMeta(row, col).isWritable) { return; } texteditor.isCellEdited = true; if (useOriginalValue) { var original = instance.getDataAtCell(row, prop); original = Handsontable.helper.stringify(original) + (suffix || ''); keyboardProxy.val(original); texteditor.setCaretPosition(keyboardProxy, original.length); } else { keyboardProxy.val(''); } texteditor.refreshDimensions(instance, $td, keyboardProxy); keyboardProxy.parent().removeClass('htHidden'); instance.rootElement.triggerHandler('beginediting.handsontable'); setTimeout(function () { //async fix for Firefox 3.6.28 (needs manual testing) keyboardProxy.parent().css({ overflow: 'visible' }); }, 1); }
javascript
{ "resource": "" }
q12781
train
function (instance, td, row, col, prop, keyboardProxy, isCancelled, ctrlDown) { if (texteditor.triggerOnlyByDestroyer) { return; } if (texteditor.isCellEdited) { texteditor.isCellEdited = false; var val; if (isCancelled) { val = [ [texteditor.originalValue] ]; } else { val = [ [$.trim(keyboardProxy.val())] ]; } if (ctrlDown) { //if ctrl+enter and multiple cells selected, behave like Excel (finish editing and apply to all cells) var sel = instance.handsontable('getSelected'); instance.populateFromArray({row: sel[0], col: sel[1]}, val, {row: sel[2], col: sel[3]}, false, 'edit'); } else { instance.populateFromArray({row: row, col: col}, val, null, false, 'edit'); } } keyboardProxy.off(".editor"); $(td).off('.editor'); keyboardProxy.css({ width: 0, height: 0 }); keyboardProxy.parent().addClass('htHidden').css({ overflow: 'hidden' }); instance.container.find('.htBorder.current').off('.editor'); instance.rootElement.triggerHandler('finishediting.handsontable'); }
javascript
{ "resource": "" }
q12782
train
function(e) { var $this = $(this); // disable actual context-menu e.preventDefault(); e.stopImmediatePropagation(); // abort native-triggered events unless we're triggering on right click if (e.data.trigger != 'right' && e.originalEvent) { return; } if (!$this.hasClass('context-menu-disabled')) { // theoretically need to fire a show event at <menu> // http://www.whatwg.org/specs/web-apps/current-work/multipage/interactive-elements.html#context-menus // var evt = jQuery.Event("show", { data: data, pageX: e.pageX, pageY: e.pageY, relatedTarget: this }); // e.data.$menu.trigger(evt); $currentTrigger = $this; if (e.data.build) { var built = e.data.build($currentTrigger, e); // abort if build() returned false if (built === false) { return; } // dynamically build menu on invocation e.data = $.extend(true, {}, defaults, e.data, built || {}); // abort if there are no items to display if (!e.data.items || $.isEmptyObject(e.data.items)) { // Note: jQuery captures and ignores errors from event handlers if (window.console) { (console.error || console.log)("No items specified to show in contextMenu"); } throw new Error('No Items sepcified'); } // backreference for custom command type creation e.data.$trigger = $currentTrigger; op.create(e.data); } // show menu op.show.call($this, e.data, e.pageX, e.pageY); } }
javascript
{ "resource": "" }
q12783
SchemaString
train
function SchemaString (key, options) { this.enumValues = []; this.regExp = null; SchemaType.call(this, key, options, 'String'); }
javascript
{ "resource": "" }
q12784
CastError
train
function CastError (type, value) { NeopreneError.call(this, 'Cast to ' + type + ' failed for value "' + value + '"'); Error.captureStackTrace(this, arguments.callee); this.name = 'CastError'; this.type = type; this.value = value; }
javascript
{ "resource": "" }
q12785
fc
train
function fc() { for (var _len = arguments.length, params = Array(_len), _key = 0; _key < _len; _key++) { params[_key] = arguments[_key]; } return createFrontendConnector(parametrize(c, params), debug); }
javascript
{ "resource": "" }
q12786
ValidationError
train
function ValidationError (instance) { NeopreneError.call(this, "Validation failed"); Error.captureStackTrace(this, arguments.callee); this.name = 'ValidationError'; this.errors = instance.errors = {}; }
javascript
{ "resource": "" }
q12787
render
train
function render(gl, width, height, dt, batch, shader) { time+=dt var anim = Math.sin(time/1000)/2+0.5 //clear the batch to zero batch.clear() //bind before drawing batch.bind(shader) //push our sprites which may have a variety //of textures batch.push({ position: [anim*100, anim*50], shape: [128, 128], texture: tex2 }) batch.push({ position: [100, 100], shape: [128, 128], color: [1, 1, 1, 0.5], texture: tex }) batch.push({ position: [300, 100], shape: [128, 128], color: [1, 1, 1, 0.5], texcoord: [0, 0, 2.5, 2.5], texture: tex }) batch.push({ texture: null, position: [100+100*Math.sin(time/2000), 100], shape: [63, 63], color: [anim, 0, 0, 1.0] }) //we need to flush any outstanding sprites batch.draw() //and unbind it... batch.unbind() }
javascript
{ "resource": "" }
q12788
Mixed
train
function Mixed (path, options) { // make sure empty array defaults are handled if (options && options.default && Array.isArray(options.default) && 0 === options.default.length) { options.default = Array; } SchemaType.call(this, path, options); }
javascript
{ "resource": "" }
q12789
bisection
train
function bisection(array, x, low, high){ // The low and high bounds the inital slice of the array that needs to be searched // this is optional low = low || 0; high = high || array.length; var mid; while (low < high) { mid = (low + high) >> 1; if (x < array[mid]) { high = mid; } else { low = mid + 1; } } return low; }
javascript
{ "resource": "" }
q12790
model
train
function model (doc, fields) { if (!(this instanceof model)) return new model(doc, fields); Model.call(this, doc, fields); }
javascript
{ "resource": "" }
q12791
GraphObject
train
function GraphObject(obj, fields) { this.isNew = true; this.errors = undefined; this._saveError = undefined; this._validationError = undefined; // this._adhocPaths = undefined; // this._removing = undefined; // this._inserting = undefined; // this.__version = undefined; this.__getters = {}; // this.__id = undefined; // the type of container - node or relationship this._activePaths = new ActiveRoster(); var required = this.schema.requiredPaths(); for (var i = 0; i < required.length; ++i) { this._activePaths.require(required[i]); } this._doc = this._buildDoc(obj, fields); if (obj) this.set(obj, undefined, true); this._registerHooks(); }
javascript
{ "resource": "" }
q12792
train
function(row, callback) { var map = {}, value; for (var i = 0, j = row.length; i < j; i++) { value = row[i]; // transform the value to either Node, Relationship or Path map[resColumns[i]] = utils.transform(value, self); } return callback(null, map); }
javascript
{ "resource": "" }
q12793
transformData
train
function transformData(methodRegExp) { var transform = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (data) { return data; }; var re = new RegExp(methodRegExp || '.*'); // The middleware function return function transformDataMiddleware(next) { // Checks if the call should be transformed. If yes, it applies the transform function function checkAndTransform(method) { return re.test(method) ? function (req) { return next[method](req).then(function (res) { return Object.assign(res, { data: transform(res.data) }); }); } : function (req) { return next[method](req); }; } // The middleware connector: return { create: checkAndTransform('create'), read: checkAndTransform('read'), update: checkAndTransform('update'), delete: checkAndTransform('delete') }; }; }
javascript
{ "resource": "" }
q12794
checkAndTransform
train
function checkAndTransform(method) { return re.test(method) ? function (req) { return next[method](req).then(function (res) { return Object.assign(res, { data: transform(res.data) }); }); } : function (req) { return next[method](req); }; }
javascript
{ "resource": "" }
q12795
Schema
train
function Schema (obj, options) { if (!(this instanceof Schema)) return new Schema(obj, options); this.paths = {}; this.virtuals = {}; this.callQueue = []; this._indexes = []; this.methods = {}; this.statics = {}; this.tree = {}; this._requiredpaths = undefined; // set options this.options = utils.options({ // safe: true strict: true , versionKey: '__v' , minimize: true , autoIndex: true // the following are only applied at construction time // , _id: true // , id: true }, options); // build paths if (obj) { this.add(obj); } }
javascript
{ "resource": "" }
q12796
train
function() { this.comps.base.add(this.comps.background); this.comps.base.add(this.comps.label); var self = this; this.setFill(amino.colortheme.button.fill.normal); amino.getCore().on('press', this, function(e) { self.setFill(amino.colortheme.button.fill.pressed); }); amino.getCore().on("release",this,function(e) { self.setFill(amino.colortheme.button.fill.normal); }); amino.getCore().on("click",this,function(e) { var event = {type:'action',source:self}; amino.getCore().fireEvent(event); if(self.actioncb) self.actioncb(event); }); this.setFontSize(15); /** @func onAction(cb) a function to call when this button fires an action. You can also listen for the 'action' event. */ this.onAction = function(cb) { this.actioncb = cb; return this; } this.markDirty = function() { this.dirty = true; amino.dirtylist.push(this); } this.doLayout = function() { var textw = this.comps.label.font.calcStringWidth(this.getText(),this.getFontSize(),this.getFontWeight(),this.getFontStyle()); this.comps.label.setTx(Math.round((this.getW()-textw)/2)); var texth = this.comps.label.font.getHeight(this.getFontSize(),this.getFontWeight(),this.getFontStyle()); this.comps.label.setTy(Math.round(this.getH()/2 + texth/2)); } this.validate = function() { this.doLayout(); this.dirty = false; } }
javascript
{ "resource": "" }
q12797
hasPrefix
train
function hasPrefix(text, prefix) { let exp = new RegExp(`^${prefix.pattern}`); let result = exp.test(text); if (prefix.antipattern) { let exp = new RegExp(`^${prefix.antipattern}`); result = result && !exp.test(text); } return result; }
javascript
{ "resource": "" }
q12798
hasSuffix
train
function hasSuffix(text, suffix) { let exp = new RegExp(`${suffix.pattern}$`); let result = exp.test(text); if (suffix.antipattern) { let exp = new RegExp(`${suffix.antipattern}$`); result = result && !exp.test(text); } return result; }
javascript
{ "resource": "" }
q12799
matchLength
train
function matchLength(text, exp) { const match = text.match(exp); return match ? match[0].length : 0; }
javascript
{ "resource": "" }