_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q64600
test
function( table ) { table = $( table )[ 0 ]; var overallWidth, percent, $tbodies, len, index, c = table.config, $colgroup = c.$table.children( 'colgroup' ); // remove plugin-added colgroup, in case we need to refresh the widths if ( $colgroup.length && $colgroup.hasClass( ts.css.colgroup ) ) { $colgroup.remove(); } if ( c.widthFixed && c.$table.children( 'colgroup' ).length === 0 ) { $colgroup = $( '<colgroup class="' + ts.css.colgroup + '">' ); overallWidth = c.$table.width(); // only add col for visible columns - fixes #371 $tbodies = c.$tbodies.find( 'tr:first' ).children( ':visible' ); len = $tbodies.length; for ( index = 0; index < len; index++ ) { percent = parseInt( ( $tbodies.eq( index ).width() / overallWidth ) * 1000, 10 ) / 10 + '%'; $colgroup.append( $( '<col>' ).css( 'width', percent ) ); } c.$table.prepend( $colgroup ); } }
javascript
{ "resource": "" }
q64601
test
function( str ) { str = ( str || '' ).replace( ts.regex.spaces, ' ' ).replace( ts.regex.shortDateReplace, '/' ); return ts.regex.shortDateTest.test( str ); }
javascript
{ "resource": "" }
q64602
checkCallExpression
test
function checkCallExpression(node) { var callee = node.callee; if (callee.type === 'Identifier' && callee.name === 'require') { var pathNode = node.arguments[0]; if (pathNode.type === 'Literal') { var p = pathNode.value; // Only check relatively-imported modules. if (startswith(p, ['/', './', '../'])) { return !endswith(p, '.js'); } } } return true; }
javascript
{ "resource": "" }
q64603
test
function(event, listener){ switch (event) { case "log": bus.subscribe(EVENT_BUSLINE, { onRemoteLogReceived: function(logObj){ listener(logObj); } }); break; default: console.error("[LOGIA] Unknown event name: '" + event + "'"); } }
javascript
{ "resource": "" }
q64604
createGitRepository
test
function createGitRepository(basePath, options) { if (typeof (options) === "undefined") options = defaultRepositoryOptions; var gitRepository = new GitRepository(); configureGitRepository(gitRepository, basePath, options); return gitRepository; }
javascript
{ "resource": "" }
q64605
recoverPubKey
test
function recoverPubKey(curve, e, signature, i) { assert.strictEqual(i & 3, i, 'Recovery param is more than two bits') var n = curve.n var G = curve.G var r = signature.r var s = signature.s assert(r.signum() > 0 && r.compareTo(n) < 0, 'Invalid r value') assert(s.signum() > 0 && s.compareTo(n) < 0, 'Invalid s value') // A set LSB signifies that the y-coordinate is odd var isYOdd = i & 1 // The more significant bit specifies whether we should use the // first or second candidate key. var isSecondKey = i >> 1 // 1.1 Let x = r + jn var x = isSecondKey ? r.add(n) : r var R = curve.pointFromX(isYOdd, x) // 1.4 Check that nR is at infinity var nR = R.multiply(n) assert(curve.isInfinity(nR), 'nR is not a valid curve point') // Compute -e from e var eNeg = e.negate().mod(n) // 1.6.1 Compute Q = r^-1 (sR - eG) // Q = r^-1 (sR + -eG) var rInv = r.modInverse(n) var Q = R.multiplyTwo(s, G, eNeg).multiply(rInv) curve.validate(Q) return Q }
javascript
{ "resource": "" }
q64606
calcPubKeyRecoveryParam
test
function calcPubKeyRecoveryParam(curve, e, signature, Q) { for (var i = 0; i < 4; i++) { var Qprime = recoverPubKey(curve, e, signature, i) // 1.6.2 Verify Q if (Qprime.equals(Q)) { return i } } throw new Error('Unable to find valid recovery factor') }
javascript
{ "resource": "" }
q64607
test
function (permissions) { _.merge(this.permissions, permissions, function (a, b) { return _.isArray(a) ? a.concat(b) : undefined; }); return this; }
javascript
{ "resource": "" }
q64608
test
function (roles) { if (!Array.isArray(roles)) { roles = [roles]; } this.permissions = _.reduce(this.permissions, function (result, actions, key) { if (roles.indexOf(key) === -1) { result[key] = actions; } return result; }, {}); return this; }
javascript
{ "resource": "" }
q64609
DAOImplementation
test
function DAOImplementation(config) { let basePath = config.basePath || 'backend/persistence/catalog/'; let isDBloaded = true; if (config.filename) { config.filename = basePath + config.filename; } if (config.schema) { this.schema = fs.readJSON(path.join(appRoot.toString(), basePath, config.schema)); } else { this.schema = {}; } let db = new DataStore(config); if (config.filename && !config.autoload) { isDBloaded = false; } this.collection = db; this.isDBloaded = isDBloaded; }
javascript
{ "resource": "" }
q64610
Model
test
function Model(attributes) { // Set events hash now to prevent proxy trap this._events = {}; // Call super constructor EventEmitter.call(this); attributes = attributes || {}; // Separator for change events this._separator = ':'; // Internal Object for storing attributes this.attributes = {}; // Attributes that have changed since the last `change` was called. this._changed = {}; // Hash of attributes that have changed silently since the last `change` // was called. this._silent = {}; // Hash of changed attributes that have changed since the last `change` // call began. this._pending = {}; // Set initial attributes silently this.set(attributes, { silent: true }); // Reset changes this._changes = {}; this._silent = {}; this._pending = {}; // Keep track of previous values (before the previous change call) this._previous = _.clone(this.attributes); // Call initialize logic this.initialize.apply(this, arguments); }
javascript
{ "resource": "" }
q64611
ProxiedModel
test
function ProxiedModel(attributes) { var model; if (attributes instanceof Model) { // Use existing model model = attributes; } else { // Create a new Model model = new Model(attributes); } // Return the Proxy handler return createModelProxy(model); }
javascript
{ "resource": "" }
q64612
createModelProxy
test
function createModelProxy(model) { // Create a Proxy handle var handle = { getOwnPropertyDescriptor: function(target, name) { return ObjProto.getOwnPropertyDescriptor.call(model.attributes, name); }, getOwnPropertyNames: function(target) { return ObjProto.getOwnPropertyNames.call(model.attributes); }, defineProperty: function(name, propertyDescriptor) { return Object.defineProperty(model.attributes, name, propertyDescriptor); }, // Get an attribute from the Model. This will first check for Model properties before // checking the Model's internal attributes map. get: function(target, name, reciever) { // Check for direct properties to satisfy internal attribute and function calls if (model[name]) { return model[name]; } // It's not a property, check for internal attribute value return model.get(name); }, set: function(target, name, value, receiver) { return model.set(name, value); }, delete: function(name) { model.unset(name); }, has: function(target, name) { return model.has('name'); }, hasOwn: function(target, name) { return this.has(target, name); }, enumerate: function(target) { return model.attributes; }, keys: function(target) { return Object.keys(model.attributes); } //protect: function(operation, target) -> boolean //stopTrapping: function(target) -> boolean //iterate: not implemented yet }; return ProxyCtor.create(handle, Model); }
javascript
{ "resource": "" }
q64613
test
function(target, name, reciever) { // Check for direct properties to satisfy internal attribute and function calls if (model[name]) { return model[name]; } // It's not a property, check for internal attribute value return model.get(name); }
javascript
{ "resource": "" }
q64614
detectDestType
test
function detectDestType(dest) { if (grunt.util._.endsWith(dest, '/')) { return cnst.directory; } else { return cnst.file; } }
javascript
{ "resource": "" }
q64615
test
function() { return { r: Math.floor(Math.random() * 256), g: Math.floor(Math.random() * 256), b: Math.floor(Math.random() * 256), a: 255 }; }
javascript
{ "resource": "" }
q64616
test
function(fn) { for (var y = 0; y < this.getHeight(); y++) { for (var x = 0; x < this.getWidth(); x++) { var rgba = this.getColor(x, y); var out = fn.call(this, x, y, rgba); this.setColor(x, y, (out || rgba)); } } return this; }
javascript
{ "resource": "" }
q64617
test
function(x, y) { var i = this._getIndex(x, y); return { r: this._png.data[i + 0], g: this._png.data[i + 1], b: this._png.data[i + 2], a: this._png.data[i + 3] }; }
javascript
{ "resource": "" }
q64618
test
function(x, y, rgba) { var i = this._getIndex(x, y); var prev = this.getColor(x, y); this._png.data[i + 0] = is_num(rgba.r) ? to_rgba_int(rgba.r): prev.r; this._png.data[i + 1] = is_num(rgba.g) ? to_rgba_int(rgba.g): prev.g; this._png.data[i + 2] = is_num(rgba.b) ? to_rgba_int(rgba.b): prev.b; this._png.data[i + 3] = is_num(rgba.a) ? to_rgba_int(rgba.a): prev.a; return this.getColor(x, y); }
javascript
{ "resource": "" }
q64619
test
function(factor) { factor = clamp(to_int(factor), 1); var width = this.getWidth() * factor; var height = this.getHeight() * factor; var buf = new buffer(width, height); for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { var i = get_index(width, x, y); var rgba = this.getColor(to_int(x / factor), to_int(y / factor)); buf[i + 0] = rgba.r; buf[i + 1] = rgba.g; buf[i + 2] = rgba.b; buf[i + 3] = rgba.a; } } this._png.width = width; this._png.height = height; this._png.data = buf; return this; }
javascript
{ "resource": "" }
q64620
test
function(fn) { fn = fn || console.log.bind(console); var buffers = []; var base64 = new Stream(); base64.readable = base64.writable = true; base64.write = function(data) { buffers.push(data); }; base64.end = function() { fn(Buffer.concat(buffers).toString('base64')); } this._png.pack().pipe(base64); }
javascript
{ "resource": "" }
q64621
test
function(fn) { fn = fn || console.log.bind(console); return this.toBase64(function(str) { fn('data:image/png;base64,' + str); }); }
javascript
{ "resource": "" }
q64622
deepest
test
function deepest(a, b, ca, cb) { if (a === b) { return true; } else if (typeof a !== 'object' || typeof b !== 'object') { return false; } else if (a === null || b === null) { return false; } else if (Buffer.isBuffer(a) && Buffer.isBuffer(b)) { if (fastEqual) { return fastEqual.call(a, b); } else { if (a.length !== b.length) return false; for (var i = 0; i < a.length; i++) if (a[i] !== b[i]) return false; return true; } } else if (a instanceof Date && b instanceof Date) { return a.getTime() === b.getTime(); } else if (isArguments(a) || isArguments(b)) { if (!(isArguments(a) && isArguments(b))) return false; var slice = Array.prototype.slice; return deepest(slice.call(a), slice.call(b), ca, cb); } else { if (a.constructor !== b.constructor) return false; var pa = Object.getOwnPropertyNames(a); var pb = Object.getOwnPropertyNames(b); if (pa.length !== pb.length) return false; var cal = ca.length; while (cal--) if (ca[cal] === a) return cb[cal] === b; ca.push(a); cb.push(b); pa.sort(); pb.sort(); for (var j = pa.length - 1; j >= 0; j--) if (pa[j] !== pb[j]) return false; var name, da, db; for (var k = pa.length - 1; k >= 0; k--) { name = pa[k]; da = Object.getOwnPropertyDescriptor(a, name); db = Object.getOwnPropertyDescriptor(b, name); if (da.enumerable !== db.enumerable || da.writable !== db.writable || da.configurable !== db.configurable || da.get !== db.get || da.set !== db.set) { return false; } if (!deepest(da.value, db.value, ca, cb)) return false; } ca.pop(); cb.pop(); return true; } }
javascript
{ "resource": "" }
q64623
assertParasite
test
function assertParasite(fn) { return function _deeperAssert() { if (this._bailedOut) return; var res = fn.apply(tap.assert, arguments); this.result(res); return res; }; }
javascript
{ "resource": "" }
q64624
getIgnored
test
function getIgnored(filepath) { for (var i in options.ignore) { if (filepath.indexOf(options.ignore[i]) !== -1) { return options.ignore[i]; } } return null; }
javascript
{ "resource": "" }
q64625
renderInputPrompt
test
function renderInputPrompt() { process.stdout.write(prefix); process.stdout.write(textToRender.join('')); }
javascript
{ "resource": "" }
q64626
calculateFieldColor
test
function calculateFieldColor(selectedColor, nonSelectedColor, focusedColor, index, out) { if(selected.indexOf(index) !== -1 && focused == index) return chalk.bold.rgb(selectedColor.r, selectedColor.g, selectedColor.b)(out); if(selected.indexOf(index) !== -1) // this goes before focused so selected color gets priority over focused values return chalk.rgb(selectedColor.r, selectedColor.g, selectedColor.b)(out); if(focused == index) return chalk.bold.rgb(focusedColor.r, focusedColor.g, focusedColor.b)(out); return chalk.rgb(nonSelectedColor.r, nonSelectedColor.g, nonSelectedColor.b)(out); }
javascript
{ "resource": "" }
q64627
render
test
function render(errors) { if (!errors) { return ''; }; return errors.map(function(error) { return error.line + ':' + error.column + ' ' + ' - ' + error.message + ' (' + error.ruleId +')'; }).join('\n'); }
javascript
{ "resource": "" }
q64628
test
function(url) { let request = parseRequest(url); let resource = getRequestedResource(request); return resource.get(request) .then(returnGetResponse); function returnGetResponse(result) { // eslint-disable-line require-jsdoc return new RESTResponse(url, "GET", result); } }
javascript
{ "resource": "" }
q64629
test
function(url, data) { let request = parseRequest(url, data); let resource = getRequestedResource(request); return resource.put(request) .then(returnResponse); function returnResponse(result) { // eslint-disable-line require-jsdoc return new RESTResponse(url, "PUT", result); } }
javascript
{ "resource": "" }
q64630
mapPrune
test
function mapPrune(input, schema) { var result = {}; _.forOwn(schema, function (value, key) { if (_.isPlainObject(value)) { // Recursive. result[key] = mapPrune(input[key] || {}, value); } else { // Base. Null is set as the default value. result[key] = input[key] || null; } }); return result; }
javascript
{ "resource": "" }
q64631
createYamlSchema
test
function createYamlSchema(customTypes) { var yamlTypes = []; _.each(customTypes, function(resolver, tagAndKindString) { var tagAndKind = tagAndKindString.split(/\s+/), yamlType = new yaml.Type(tagAndKind[0], { kind: tagAndKind[1], construct: function(data) { var result = resolver.call(this, data, loadYamlFile); if (_.isUndefined(result) || _.isFunction(result)) { return null; } else { return result; } } }); yamlTypes.push(yamlType); }); return yaml.Schema.create(yamlTypes); }
javascript
{ "resource": "" }
q64632
loadYamlFile
test
function loadYamlFile(filepath) { try { return yaml.safeLoad( fs.readFileSync(filepath), { schema: yamlSchema, filename: filepath } ); } catch (err) { return null; } }
javascript
{ "resource": "" }
q64633
loadTheme
test
function loadTheme(props) { var relPath = '/' + props.join('/') + '.yml', defaultsPath = path.resolve(base + '/scss/themes/default' + relPath), customPath = (custom) ? custom + relPath : null, defaultVars = {}, customVars = null, result = {}; // Try loading a custom theme file customVars = loadYamlFile(customPath); // If merge mode is set to "replace", don't even load the defaults if (customVars && customVars['merge-mode'] === 'replace') { result = _.omit(customVars, 'merge-mode'); } else { defaultVars = loadYamlFile(defaultsPath); result = _.merge(defaultVars, customVars); } // Store variables in cached theme var _.set(theme, props.join('.'), result); return result; }
javascript
{ "resource": "" }
q64634
luiTheme
test
function luiTheme(props) { var propsS = (_.isArray(props)) ? props.join('.') : props, propsA = (_.isString(props)) ? props.split('.') : props, objectVars, objectPath = []; objectVars = _.result(theme, propsS); // If object is already cached in theme, return it if (objectVars) { return objectVars; // Else load it from file } else { // Find the object fromp build file _.each(propsA, function(prop) { if (_.result(build, _.union(objectPath, [prop]).join('.')) || (_.includes(_.result(build, objectPath.join('.')), prop))) { objectPath.push(prop); } else { return objectPath; } }); loadTheme(objectPath); return _.result(theme, propsS); } }
javascript
{ "resource": "" }
q64635
write
test
function write(destination, data, callback) { // Create directories if needs be mkdirp(path.dirname(destination), null, (err, made) => { if (err) { console.error(err); } else { fs.writeFile(destination, data, (err) => { if (err) { console.error(err); } if (typeof(callback) == 'function') { callback(destination, data); } }); } }); return destination; }
javascript
{ "resource": "" }
q64636
init
test
function init(_options) { // Build global options var options = _.merge(defaults, _options); // Store paths base = options.base; custom = options.custom; // Retrieve build definition build = options.build = (typeof options.build === 'object') ? options.build : require(options.build); // Create YAML schema (create custom types) yamlSchema = createYamlSchema(options.customTypes); return options; }
javascript
{ "resource": "" }
q64637
redact
test
function redact(_options, callback) { var imports = [], // List of scss to import output = '', // The scss output errors = []; // List of errors encountered // Build core theme['core'] = {}; _.each(_options.build.core, function(objects, family) { theme['core'][family] = {}; _.each(objects, function(objectName) { luiTheme('core.' + family + '.' + objectName); imports.push('core/' + family + '/' + objectName); }); }); // Build plugins if (_options.build.plugins) { theme['plugins'] = {}; _.each(_options.build.plugins, function(plugin) { luiTheme('plugins.' + plugin); }); } output = tosass.format({theme: theme, imports: imports}); if (typeof(callback) === 'function') { callback(output); } return output; }
javascript
{ "resource": "" }
q64638
test
function(_options, callback) { var options = init(_options); return write(options.dest, redact(options), callback); }
javascript
{ "resource": "" }
q64639
test
function(map) { return '(' + Object.keys(map).map(function (key) { return key + ': ' + parseValue(map[key]); }).join(',') + ')'; }
javascript
{ "resource": "" }
q64640
objectToSass
test
function objectToSass(object) { return Object.keys(object).map(function (key) { return '$' + key + ': ' + parseValue(object[key]) + ';'; }).join('\n'); }
javascript
{ "resource": "" }
q64641
parseValue
test
function parseValue(value) { if (_.isArray(value)) return converters.list(value); else if (_.isPlainObject(value)) return converters.map(value); else return value; }
javascript
{ "resource": "" }
q64642
domSafeRandomGuid
test
function domSafeRandomGuid() { var _arguments = arguments; var _again = true; _function: while (_again) { numberOfBlocks = output = num = undefined; var s4 = function s4() { return Math.floor((1 + Math.random()) * 65536).toString(16).substring(1); }; _again = false; var numberOfBlocks = _arguments[0] === undefined ? 4 : _arguments[0]; var output = ''; var num = numberOfBlocks; while (num > 0) { output += s4(); if (num > 1) output += '-'; num--; } if (null === document.getElementById(output)) { return output; } else { _arguments = [numberOfBlocks]; _again = true; continue _function; } } }
javascript
{ "resource": "" }
q64643
objectProperty
test
function objectProperty (obj, indentLength = 1, inArray = 0) { if (Object.keys(obj).length === 0) { return ' {}'; } let str = '\n'; const objectPrefix = getPrefix(indentLength, indentChars); Object .keys(obj) .forEach((name) => { const value = obj[name]; const type = typeOf(value); const inArrayPrefix = getPrefix(inArray, ' '); const afterPropsIndent = NO_INDENT_TYPES.includes(type) ? '' : ' '; const valueString = checkCircular(value) ? ' [Circular]' : typifiedString(type, value, indentLength + 1, inArray); str += `${ inArrayPrefix }${ objectPrefix }${ name }:${ afterPropsIndent }${ valueString }\n`; }); return str.substring(0, str.length - 1); }
javascript
{ "resource": "" }
q64644
arrayProperty
test
function arrayProperty (values, indentLength = 1, inArray = 0) { if (values.length === 0) { return ' []'; } let str = '\n'; const arrayPrefix = getPrefix(indentLength, indentChars); values .forEach((value) => { const type = typeOf(value); const inArrayPrefix = getPrefix(inArray, ' '); const valueString = checkCircular(value) ? '[Circular]' : typifiedString(type, value, indentLength, inArray + 1) .toString() .trimLeft(); str += `${ inArrayPrefix }${ arrayPrefix }- ${ valueString }\n`; }); return str.substring(0, str.length - 1); }
javascript
{ "resource": "" }
q64645
RESTResponse
test
function RESTResponse(url, method, body) { /** The original request. */ this.request = { url: url, method: method }; /** The body of the response. */ this.body = body || ""; /** Status of the response. */ this.status = "200"; }
javascript
{ "resource": "" }
q64646
test
function (map, receive) { var entries = mapEntries.call(map); var next; do { next = entries.next(); } while (!next.done && receive(next.value)); }
javascript
{ "resource": "" }
q64647
test
function(component) { var id = component.getId(); // <debug> if (this.map[id]) { Ext.Logger.warn('Registering a component with a id (`' + id + '`) which has already been used. Please ensure the existing component has been destroyed (`Ext.Component#destroy()`.'); } // </debug> this.map[component.getId()] = component; }
javascript
{ "resource": "" }
q64648
test
function(component, defaultType) { if (component.isComponent) { return component; } else if (Ext.isString(component)) { return Ext.createByAlias('widget.' + component); } else { var type = component.xtype || defaultType; return Ext.createByAlias('widget.' + type, component); } }
javascript
{ "resource": "" }
q64649
rns
test
function rns() { let jargv = _.$('env.jargv') let key = _.get(jargv, '_[0]') let prop = key ? _.get(snapptop, key) : null if(!_.isFunction(prop)) return _.log(`\nApi.Method ${key || 'NO KEY'} not found\n`) _.log(`\nRunnng test: ${key}\n`) _.log(jargv) _.log() jargv = _.omit(jargv, ['_']) var ret = _.attempt(prop, jargv, (err, result) => { if(err) return _.log(err) _.log(result) }) if(_.isError(ret)) _.log(ret) return ret }
javascript
{ "resource": "" }
q64650
test
function (node) { var result = '', i, n, attr, child; if (node.nodeType === document.TEXT_NODE) { return node.nodeValue; } result += '<' + node.nodeName; if (node.attributes.length) { for (i = 0, n = node.attributes.length; i < n; i++) { attr = node.attributes[i]; result += ' ' + attr.name + '="' + attr.value + '"'; } } result += '>'; if (node.childNodes && node.childNodes.length) { for (i = 0, n = node.childNodes.length; i < n; i++) { child = node.childNodes[i]; result += this.serializeNode(child); } } result += '</' + node.nodeName + '>'; return result; }
javascript
{ "resource": "" }
q64651
test
function(name, namespace) { var dom = this.dom; return dom.getAttributeNS(namespace, name) || dom.getAttribute(namespace + ":" + name) || dom.getAttribute(name) || dom[name]; }
javascript
{ "resource": "" }
q64652
test
function (rules) { this._instantiatedDate = new Date(); this._instanceCount = 0; this._propertyCount = 0; this._collatedInstances = null; this._rules = (rules && this._checkRules(rules)) || []; this.initEventualSchema(); }
javascript
{ "resource": "" }
q64653
test
function(sorters, defaultDirection) { var currentSorters = this.getSorters(); return this.insertSorters(currentSorters ? currentSorters.length : 0, sorters, defaultDirection); }
javascript
{ "resource": "" }
q64654
test
function(index, sorters, defaultDirection) { // We begin by making sure we are dealing with an array of sorters if (!Ext.isArray(sorters)) { sorters = [sorters]; } var ln = sorters.length, direction = defaultDirection || this.getDefaultSortDirection(), sortRoot = this.getSortRoot(), currentSorters = this.getSorters(), newSorters = [], sorterConfig, i, sorter, currentSorter; if (!currentSorters) { // This will guarantee that we get the collection currentSorters = this.createSortersCollection(); } // We first have to convert every sorter into a proper Sorter instance for (i = 0; i < ln; i++) { sorter = sorters[i]; sorterConfig = { direction: direction, root: sortRoot }; // If we are dealing with a string we assume it is a property they want to sort on. if (typeof sorter === 'string') { currentSorter = currentSorters.get(sorter); if (!currentSorter) { sorterConfig.property = sorter; } else { if (defaultDirection) { currentSorter.setDirection(defaultDirection); } else { // If we already have a sorter for this property we just toggle its direction. currentSorter.toggle(); } continue; } } // If it is a function, we assume its a sorting function. else if (Ext.isFunction(sorter)) { sorterConfig.sorterFn = sorter; } // If we are dealing with an object, we assume its a Sorter configuration. In this case // we create an instance of Sorter passing this configuration. else if (Ext.isObject(sorter)) { if (!sorter.isSorter) { if (sorter.fn) { sorter.sorterFn = sorter.fn; delete sorter.fn; } sorterConfig = Ext.apply(sorterConfig, sorter); } else { newSorters.push(sorter); if (!sorter.getRoot()) { sorter.setRoot(sortRoot); } continue; } } // Finally we get to the point where it has to be invalid // <debug> else { Ext.Logger.warn('Invalid sorter specified:', sorter); } // </debug> // If a sorter config was created, make it an instance sorter = Ext.create('Ext.util.Sorter', sorterConfig); newSorters.push(sorter); } // Now lets add the newly created sorters. for (i = 0, ln = newSorters.length; i < ln; i++) { currentSorters.insert(index + i, newSorters[i]); } this.dirtySortFn = true; if (currentSorters.length) { this.sorted = true; } return currentSorters; }
javascript
{ "resource": "" }
q64655
test
function(sorters) { // We begin by making sure we are dealing with an array of sorters if (!Ext.isArray(sorters)) { sorters = [sorters]; } var ln = sorters.length, currentSorters = this.getSorters(), i, sorter; for (i = 0; i < ln; i++) { sorter = sorters[i]; if (typeof sorter === 'string') { currentSorters.removeAtKey(sorter); } else if (typeof sorter === 'function') { currentSorters.each(function(item) { if (item.getSorterFn() === sorter) { currentSorters.remove(item); } }); } else if (sorter.isSorter) { currentSorters.remove(sorter); } } if (!currentSorters.length) { this.sorted = false; } }
javascript
{ "resource": "" }
q64656
test
function(items, item, sortFn, containsItem) { var start = 0, end = items.length - 1, sorterFn = sortFn || this.getSortFn(), middle, comparison; while (start < end || start === end && !containsItem) { middle = (start + end) >> 1; var middleItem = items[middle]; if (middleItem === item) { start = middle; break; } comparison = sorterFn(item, middleItem); if (comparison > 0 || (!containsItem && comparison === 0)) { start = middle + 1; } else if (comparison < 0) { end = middle - 1; } else if (containsItem && (start !== end)) { start = middle + 1; } } return start; }
javascript
{ "resource": "" }
q64657
test
function(attribute, newValue) { var input = this.input; if (!Ext.isEmpty(newValue, true)) { input.dom.setAttribute(attribute, newValue); } else { input.dom.removeAttribute(attribute); } }
javascript
{ "resource": "" }
q64658
test
function() { var el = this.input, checked; if (el) { checked = el.dom.checked; this._checked = checked; } return checked; }
javascript
{ "resource": "" }
q64659
test
function() { var me = this, el = me.input; if (el && el.dom.focus) { el.dom.focus(); } return me; }
javascript
{ "resource": "" }
q64660
test
function() { var me = this, el = this.input; if (el && el.dom.blur) { el.dom.blur(); } return me; }
javascript
{ "resource": "" }
q64661
test
function() { var me = this, el = me.input; if (el && el.dom.setSelectionRange) { el.dom.setSelectionRange(0, 9999); } return me; }
javascript
{ "resource": "" }
q64662
test
function(date, format) { if (utilDate.formatFunctions[format] == null) { utilDate.createFormat(format); } var result = utilDate.formatFunctions[format].call(date); return result + ''; }
javascript
{ "resource": "" }
q64663
test
function(date, interval, value) { var d = Ext.Date.clone(date); if (!interval || value === 0) return d; switch(interval.toLowerCase()) { case Ext.Date.MILLI: d= new Date(d.valueOf() + value); break; case Ext.Date.SECOND: d= new Date(d.valueOf() + value * 1000); break; case Ext.Date.MINUTE: d= new Date(d.valueOf() + value * 60000); break; case Ext.Date.HOUR: d= new Date(d.valueOf() + value * 3600000); break; case Ext.Date.DAY: d= new Date(d.valueOf() + value * 86400000); break; case Ext.Date.MONTH: var day = date.getDate(); if (day > 28) { day = Math.min(day, Ext.Date.getLastDateOfMonth(Ext.Date.add(Ext.Date.getFirstDateOfMonth(date), 'mo', value)).getDate()); } d.setDate(day); d.setMonth(date.getMonth() + value); break; case Ext.Date.YEAR: d.setFullYear(date.getFullYear() + value); break; } return d; }
javascript
{ "resource": "" }
q64664
test
function (min, max, unit) { var ExtDate = Ext.Date, est, diff = +max - min; switch (unit) { case ExtDate.MILLI: return diff; case ExtDate.SECOND: return Math.floor(diff / 1000); case ExtDate.MINUTE: return Math.floor(diff / 60000); case ExtDate.HOUR: return Math.floor(diff / 3600000); case ExtDate.DAY: return Math.floor(diff / 86400000); case 'w': return Math.floor(diff / 604800000); case ExtDate.MONTH: est = (max.getFullYear() * 12 + max.getMonth()) - (min.getFullYear() * 12 + min.getMonth()); if (Ext.Date.add(min, unit, est) > max) { return est - 1; } else { return est; } case ExtDate.YEAR: est = max.getFullYear() - min.getFullYear(); if (Ext.Date.add(min, unit, est) > max) { return est - 1; } else { return est; } } }
javascript
{ "resource": "" }
q64665
test
function (date, unit, step) { var num = new Date(+date); switch (unit.toLowerCase()) { case Ext.Date.MILLI: return num; break; case Ext.Date.SECOND: num.setUTCSeconds(num.getUTCSeconds() - num.getUTCSeconds() % step); num.setUTCMilliseconds(0); return num; break; case Ext.Date.MINUTE: num.setUTCMinutes(num.getUTCMinutes() - num.getUTCMinutes() % step); num.setUTCSeconds(0); num.setUTCMilliseconds(0); return num; break; case Ext.Date.HOUR: num.setUTCHours(num.getUTCHours() - num.getUTCHours() % step); num.setUTCMinutes(0); num.setUTCSeconds(0); num.setUTCMilliseconds(0); return num; break; case Ext.Date.DAY: if (step == 7 || step == 14){ num.setUTCDate(num.getUTCDate() - num.getUTCDay() + 1); } num.setUTCHours(0); num.setUTCMinutes(0); num.setUTCSeconds(0); num.setUTCMilliseconds(0); return num; break; case Ext.Date.MONTH: num.setUTCMonth(num.getUTCMonth() - (num.getUTCMonth() - 1) % step,1); num.setUTCHours(0); num.setUTCMinutes(0); num.setUTCSeconds(0); num.setUTCMilliseconds(0); return num; break; case Ext.Date.YEAR: num.setUTCFullYear(num.getUTCFullYear() - num.getUTCFullYear() % step, 1, 1); num.setUTCHours(0); num.setUTCMinutes(0); num.setUTCSeconds(0); num.setUTCMilliseconds(0); return date; break; } }
javascript
{ "resource": "" }
q64666
getOptions
test
function getOptions(messageType) { const options = Object.assign({}, _defaults); if (messageType in _options) { Object.assign(options, _options[messageType]); } return options; }
javascript
{ "resource": "" }
q64667
parse
test
function parse(messageType, args) { const options = getOptions(messageType); /** Interpreter */ if (typeof options.interpreter === "function") { for (const index in args) { /** Let string be without additional ' ' */ if (typeof args[index] === "string") { continue; } args[index] = options.interpreter(args[index]); } } /** Label */ if (options.labels) { args.unshift(`[${messageType.toUpperCase()}]`); } /** Timestamp */ if (options.timestamp) { switch (typeof options.timestamp) { case "boolean": args.unshift(`[${new Date().toLocaleString()}]`); break; case "string": args.unshift(`[${moment().format(options.timestamp)}]`); break; default: throw new Error(`Invalid timestamp type (${typeof options.timestamp}). Should be (boolean | string)`); } } return args.join(" "); }
javascript
{ "resource": "" }
q64668
stdout
test
function stdout(messageType) { return (...args) => { const options = getOptions(messageType); let message = parse(messageType, args); /** Add trace to console.trace */ if (messageType === "trace") { message += `\n${getTrace()}`; } /** Stdout to console */ if (!options.fileOnly) { _console.log(message); } /** Stdout to file */ if (typeof options.filePath === "string" && options.filePath.length > 0) { fs.appendFileSync(options.filePath, `${message}\n`); } }; }
javascript
{ "resource": "" }
q64669
assignOptions
test
function assignOptions(defaults, userDefined) { for (const optionKey in userDefined) { if (defaults.hasOwnProperty(optionKey)) { defaults[optionKey] = userDefined[optionKey]; } else { throw new Error(`Unknown {IOptions} parameter '${optionKey}'`); } } return defaults; }
javascript
{ "resource": "" }
q64670
test
function (pagesPath, allPartials) { if (options.verbose) { grunt.log.writeln('- using pages path: %s', pagesPath); } var allPages = {}; // load fileGlobals from file in [src]/globals.json if (grunt.file.exists(options.src + '/globals.json')) { fileGlobals = grunt.file.readJSON(options.src + '/globals.json'); gruntGlobals = mergeObj(gruntGlobals, fileGlobals); } // for all files in dir grunt.file.recurse(pagesPath, function (absPath, rootDir, subDir, fileName) { // file extension does not match - ignore if (!fileName.match(tplMatcher)) { if (options.verbose) { grunt.log.writeln('-- ignoring file: %s', fileName); } return; } var pageName = absPath.replace(rootDir, '').replace(tplMatcher, '').substring(1), pageSrc = grunt.file.read(absPath), pageJson = {}, dataPath = absPath.replace(tplMatcher, '.json'), compiledPage = Hogan.compile(pageSrc); // , { sectionTags: [{o:'_i', c:'i'}] } if (options.verbose) { grunt.log.writeln('-- compiled page: %s', pageName); } // read page data from {pageName}.json if (grunt.file.exists(dataPath)) { if (options.verbose) { grunt.log.writeln('--- using page data from: %s', dataPath); } pageJson = grunt.file.readJSON(dataPath); pageData[pageName] = mergeObj(gruntGlobals, pageJson); if (options.verbose) { grunt.log.writeln('--- json for %s', pageName, pageData[pageName]); } } else { pageData[pageName] = gruntGlobals; } allPages[pageName] = compiledPage.render(pageData[pageName], allPartials); }); return allPages; }
javascript
{ "resource": "" }
q64671
test
function(result) { // Write result to file if it was opened if (fd && result.slice(0, 3) !== '[D]' && result.match(/\u001b\[/g) === null) { fs.writeSync(fd, result); } // Prevent the original process.stdout.write from executing if quiet was specified if (options.quiet) { return hooker.preempt(); } }
javascript
{ "resource": "" }
q64672
test
function(cb, param) { return function() { var args = Array.prototype.slice.call(arguments, 1); if(typeof param !== 'undefined') { args.unshift(param); } else if (arguments.length === 1) { args.unshift(arguments[0]); } args.unshift(null); cb.apply(null, args); }; }
javascript
{ "resource": "" }
q64673
test
function(callback) { if (tunnel) { return callback(null); } grunt.log.debug('checking if selenium is running'); var options = { host: capabilities.host || 'localhost', port: capabilities.port || 4444, path: '/wd/hub/status' }; http.get(options, function() { grunt.log.debug('selenium is running'); isSeleniumServerRunning = true; callback(null); }).on('error', function() { grunt.log.debug('selenium is not running'); callback(null); }); }
javascript
{ "resource": "" }
q64674
test
function(callback) { if (tunnel || isSeleniumServerRunning) { return callback(null); } grunt.log.debug('installing driver if needed'); selenium.install(options.seleniumInstallOptions, function(err) { if (err) { return callback(err); } grunt.log.debug('driver installed'); callback(null); }); }
javascript
{ "resource": "" }
q64675
test
function() { var callback = arguments[arguments.length - 1]; grunt.log.debug('init WebdriverIO instance'); GLOBAL.browser.init(function(err) { /** * gracefully kill process if init fails */ callback(err); }); }
javascript
{ "resource": "" }
q64676
test
function(callback) { grunt.log.debug('run mocha tests'); /** * save session ID */ sessionID = GLOBAL.browser.requestHandler.sessionID; mocha.run(next(callback)); }
javascript
{ "resource": "" }
q64677
test
function(result, callback) { grunt.log.debug('end selenium session'); // Restore grunt exception handling unmanageExceptions(); // Close Remote sessions if needed GLOBAL.browser.end(next(callback, result === 0)); }
javascript
{ "resource": "" }
q64678
test
function(result) { var callback = arguments[arguments.length - 1]; if (!options.user && !options.key && !options.updateSauceJob) { return callback(null, result); } grunt.log.debug('update job on Sauce Labs'); var sauceAccount = new SauceLabs({ username: options.user, password: options.key }); sauceAccount.updateJob(sessionID, { passed: result, public: true }, next(callback, result)); }
javascript
{ "resource": "" }
q64679
test
function(result) { var callback = arguments[arguments.length - 1]; grunt.log.debug('finish grunt task'); if (isLastTask) { // close the file if it was opened if (fd) { fs.closeSync(fd); } // Restore process.stdout.write to its original value hooker.unhook(process.stdout, 'write'); } done(result); callback(); }
javascript
{ "resource": "" }
q64680
render
test
function render (req, res, body) { var response = {}; var parsedURL = parseURL(req.url); // Append URL properties for (var prop in parsedURL) response[prop] = parsedURL[prop]; // Append select `req` properties ['method', 'url'].forEach(function (prop) { response[prop] = req[prop]; }); // Append select `res` properties ['headers', 'statusCode'].forEach(function (prop) { response[prop] = res[prop]; }); response.body = body; return response; }
javascript
{ "resource": "" }
q64681
test
function (val, key) { const optVal = _M._option.getIn(key); //check for init key match if (optVal !== null) { if (_.isObject(optVal)) { //merge in option to the defaults _M._option.mergeIn(key, _.defaultsDeep(val, _M._option.getIn(key))); }else { //merge in option to the defaults _M._option.mergeIn(key, val); } } }
javascript
{ "resource": "" }
q64682
test
function (optionObj) { //@hacky fix for #388 if (_.hasIn(optionObj, ['transitionDefault'])) { _M._option.updateTransDefault(optionObj.transitionDefault); delete optionObj.transitionDefault; } //cycle to check if it option object has any global opts _.each(optionObj, function (val, key) { //if sub-object if (_.isObject(val)) { _.each(val, function (_val, _key) { mergeOption(_val, [key, _key]); }); }else { mergeOption(val, [key]); } }); }
javascript
{ "resource": "" }
q64683
test
function (key, keyType, funk, passKey = true) { //test from list, check out the util if (_H.util.regularExp.keyTest(key, keyType)) { //checks for use key const data = self.doNotUse(objectArgs.get(key), keyType); if (!data) { return true; } //send off to be processed if (passKey) { funk(key, data, target, keyType); }else { funk(data, target, keyType, key); } return true; } }
javascript
{ "resource": "" }
q64684
test
function (sourceObj) { //processing object - loop de loop for (const property in sourceObj) { if (sourceObj.hasOwnProperty(property)) { if (_.isPlainObject(sourceObj[property])) { const use = _.get(sourceObj[property], 'use'); if (useIsFalse(use)) { sourceObj = _.omit(sourceObj, property); }else { if (useIsTrue(use)) { //removes ture ueses sourceObj[property] = _.omit(sourceObj[property], 'use'); } sourceObj[property] = searchObject(sourceObj[property]); } } } } return sourceObj; }
javascript
{ "resource": "" }
q64685
add
test
function add(reducers, scope, defaultState) { if (scope === undefined) scope = "general"; // Add combine reducer _combines[scope] !== undefined || defineReducer(scope); // Add data var scopeReducers = _reducers[scope] || {}; for (var type in reducers) { var reducer = reducers[type]; if (typeof reducer === 'function') { if (scopeReducers[type] === undefined) { scopeReducers[type] = [ reducer ]; } else { scopeReducers[type].push(reducer); } } } if (defaultState !== undefined) { scopeReducers._default = defaultState; } _reducers[scope] = scopeReducers; }
javascript
{ "resource": "" }
q64686
remove
test
function remove(scope, type) { if (scope === undefined) scope = "general"; if (type === undefined) { delete _combines[scope]; delete _reducers[scope]; } else { delete _reducers[scope][type]; } }
javascript
{ "resource": "" }
q64687
replace
test
function replace(reducers, scope, defaultState) { remove(scope); add(reducers, scope, defaultState); }
javascript
{ "resource": "" }
q64688
toInteger
test
function toInteger(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber(value); if (value === INFINITY || value === -INFINITY) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } var remainder = value % 1; return value === value ? (remainder ? value - remainder : value) : 0; }
javascript
{ "resource": "" }
q64689
writeError
test
function writeError(type, file, line, message) { if (!messages[type]) { messages[type] = []; } messages[type].push({ type : type, file : file, line : line, message : message }); }
javascript
{ "resource": "" }
q64690
flushMessages
test
function flushMessages() { Object.keys(messages) .forEach(function(type) { messages[type].forEach(function(msg) { writeLine(msg.type + " error: [" + msg.file + ":" + msg.line + "] " + msg.message); }); }); }
javascript
{ "resource": "" }
q64691
getConfig
test
function getConfig(file) { var config = {}, subConfig; try { config = JSON.parse(fs.readFileSync(file, "utf8")); if (config.extends) { subConfig = JSON.parse(fs.readFileSync(config.extends, "utf8")); util._extend(subConfig, config); delete subConfig.extends; config = subConfig; } } catch (e) { // empty } return config; }
javascript
{ "resource": "" }
q64692
isIgnored
test
function isIgnored(file) { return ignorePatterns.some(function(pattern) { return minimatch(file, pattern, { nocase : true, matchBase : true }); }); }
javascript
{ "resource": "" }
q64693
extractStyles
test
function extractStyles(src) { var isInBlock = false, lines = []; src.replace(/\r/g, "").split("\n").forEach(function(l) { // we're at the end of the style tag if (l.indexOf("</style") > -1) { lines[lines.length] = ""; isInBlock = false; return; } if (isInBlock) { lines[lines.length] = l; } else { lines[lines.length] = ""; } if (l.indexOf("<style") > -1) { isInBlock = true; } }); return lines.join("\n").replace(/\{\$(\w+\.)*\w+\}/g, "{}"); }
javascript
{ "resource": "" }
q64694
read
test
function read() { var filename = process.argv[2], src = fs.readFileSync(process.argv[3], "utf8"); // attempt to modify any src passing through the pre-commit hook try { src = require(path.join(process.cwd(), ".git-hooks/pre-commit-plugins/pre-commit-modifier"))(filename, src); } catch (e) { // empty } // filename, src return Bluebird.resolve({ filename : filename, src : src }); }
javascript
{ "resource": "" }
q64695
loadFileCheckerPlugins
test
function loadFileCheckerPlugins() { var checkers = {}; try { fs.readdirSync(path.join(process.cwd(), ".git-hooks/pre-commit-plugins/plugins")) .forEach(function(file) { var check = file.replace(/\.js$/, ""); if (!(/\.js$/).test(file)) { return; } checkers[check] = require(path.join(process.cwd(), ".git-hooks/pre-commit-plugins/plugins", file)); }); } catch (e) { // empty } return checkers; }
javascript
{ "resource": "" }
q64696
test
function(oldName, newName, prefix, suffix) { if (!oldName && !newName) { return this; } oldName = oldName || []; newName = newName || []; if (!this.isSynchronized) { this.synchronize(); } if (!suffix) { suffix = ''; } var dom = this.dom, map = this.hasClassMap, classList = this.classList, SEPARATOR = this.SEPARATOR, i, ln, name; prefix = prefix ? prefix + SEPARATOR : ''; suffix = suffix ? SEPARATOR + suffix : ''; if (typeof oldName == 'string') { oldName = oldName.split(this.spacesRe); } if (typeof newName == 'string') { newName = newName.split(this.spacesRe); } for (i = 0, ln = oldName.length; i < ln; i++) { name = prefix + oldName[i] + suffix; if (map[name]) { delete map[name]; Ext.Array.remove(classList, name); } } for (i = 0, ln = newName.length; i < ln; i++) { name = prefix + newName[i] + suffix; if (!map[name]) { map[name] = true; classList.push(name); } } dom.className = classList.join(' '); return this; }
javascript
{ "resource": "" }
q64697
test
function(className) { var map = this.hasClassMap, i, ln, name; if (typeof className == 'string') { className = className.split(this.spacesRe); } for (i = 0, ln = className.length; i < ln; i++) { name = className[i]; if (!map[name]) { map[name] = true; } } this.classList = className.slice(); this.dom.className = className.join(' '); }
javascript
{ "resource": "" }
q64698
test
function(width, height) { if (Ext.isObject(width)) { // in case of object from getSize() height = width.height; width = width.width; } this.setWidth(width); this.setHeight(height); return this; }
javascript
{ "resource": "" }
q64699
test
function(prop) { var me = this, dom = me.dom, hook = me.styleHooks[prop], cs, result; if (dom == document) { return null; } if (!hook) { me.styleHooks[prop] = hook = { name: Ext.dom.Element.normalize(prop) }; } if (hook.get) { return hook.get(dom, me); } cs = window.getComputedStyle(dom, ''); // why the dom.style lookup? It is not true that "style == computedStyle" as // well as the fact that 0/false are valid answers... result = (cs && cs[hook.name]); // || dom.style[hook.name]; // WebKit returns rgb values for transparent, how does this work n IE9+ // if (!supportsTransparentColor && result == 'rgba(0, 0, 0, 0)') { // result = 'transparent'; // } return result; }
javascript
{ "resource": "" }