_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
27
233k
language
stringclasses
1 value
meta_information
dict
q28300
log
train
function log(msg, level, config) { // Don't log messages in quiet mode if (config && config.quiet) return; const logMethod = console[level] || console.log; let out = msg; if (typeof msg === 'object') {
javascript
{ "resource": "" }
q28301
cleanCode
train
function cleanCode(str) { str = str .replace(/\r\n|[\r\n\u2028\u2029]/g, '\n') // unify linebreaks .replace(/^\uFEFF/, ''); // replace zero-width no-break space str = stripFnStart(str) // replace function declaration .replace(/\)\s*\)\s*$/, ')') // replace closing paren .replace(/\s*};?\s*$/, ''); ...
javascript
{ "resource": "" }
q28302
createUnifiedDiff
train
function createUnifiedDiff({ actual, expected }) { return diff.createPatch('string', actual, expected) .split('\n') .splice(4) .map(line => { if (line.match(/@@/)) { return null; } if (line.match(/\\ No newline/)) {
javascript
{ "resource": "" }
q28303
normalizeErr
train
function normalizeErr(err, config) { const { name, message, actual, expected, stack, showDiff } = err; let errMessage; let errDiff; /** * Check that a / b have the same type. */ function sameType(a, b) { const objToString = Object.prototype.toString; return objToString.call(a) === objToString.c...
javascript
{ "resource": "" }
q28304
cleanSuite
train
function cleanSuite(suite, totalTestsRegistered, config) { let duration = 0; const passingTests = []; const failingTests = []; const pendingTests = []; const skippedTests = []; const beforeHooks = _.map( [].concat(suite._beforeAll, suite._beforeEach), test => cleanTest(test, config) ); const a...
javascript
{ "resource": "" }
q28305
mapSuites
train
function mapSuites(suite, totalTestsReg, config) { const suites = _.compact(_.map(suite.suites, subSuite => ( mapSuites(subSuite, totalTestsReg, config) )));
javascript
{ "resource": "" }
q28306
_getOption
train
function _getOption(optToGet, options, isBool, defaultValue) { const envVar = `MOCHAWESOME_${optToGet.toUpperCase()}`; if (options && typeof options[optToGet] !== 'undefined') { return (isBool &&
javascript
{ "resource": "" }
q28307
train
function (...args) { // Check args to see if we should bother continuing if ((args.length !== 2) || !isObject(args[0])) { log(ERRORS.INVALID_ARGS, 'error'); return; } const ctx = args[1]; // Ensure that context meets the requirements if (!_isValidContext(ctx)) { log(ERRORS.INVALID_CONTEXT(ctx)...
javascript
{ "resource": "" }
q28308
sendRequest
train
function sendRequest(type, options) { // Both remove and removeAll use the type 'remove' in the protocol const normalizedType = type === 'removeAll' ? 'remove' : type return socket
javascript
{ "resource": "" }
q28309
isPrimitive
train
function isPrimitive(value) { if (value === null) { return true } if (value === undefined) { return false } if (typeof value === 'function') { return false } if ([ 'boolean', 'number', 'string' ].indexOf(typeof
javascript
{ "resource": "" }
q28310
model
train
function model(inputValue$, messages$) { return Rx.Observable.combineLatest( inputValue$.startWith(null), messages$.startWith([]),
javascript
{ "resource": "" }
q28311
view
train
function view(state$) { // Displayed for each chat message. function chatMessage(msg) { return li('.message', { key: msg.id }, [ img({ height: '50', width: '50', src: `http://api.adorable.io/avatars/50/${msg.authorId}.png`, }), span('.text', msg.text), ]) ...
javascript
{ "resource": "" }
q28312
chatMessage
train
function chatMessage(msg) { return li('.message', { key: msg.id }, [ img({ height: '50', width: '50',
javascript
{ "resource": "" }
q28313
main
train
function main(sources) { const intents = intent(sources) const state$ = model(intents.inputValue$, intents.messages$)
javascript
{ "resource": "" }
q28314
makePresentable
train
function makePresentable(observable, query) { // Whether the entire data structure is in each change const pointQuery = Boolean(query.find) if (pointQuery) { let hasEmitted = false const seedVal = null // Simplest case: just pass through new_val return observable .filter(change => !hasEmitt...
javascript
{ "resource": "" }
q28315
train
function(e){ if(e.keyCode === 9){ e.preventDefault(); var cursor = this.selectionStart; var nv = this.value.substring(0,cursor), bv = this.value.substring(cursor, this.value.length);;
javascript
{ "resource": "" }
q28316
_match
train
function _match (rule, cmtData) { var path = rule.subject.split('.'); var extracted = cmtData; while (path.length > 0) { var item = path.shift(); if (item === '') { continue; } if (extracted.hasOwnProperty(item)) { e...
javascript
{ "resource": "" }
q28317
CommentFilter
train
function CommentFilter() { this.rules = []; this.modifiers = []; this.allowUnknownTypes = true; this.allowTypes = { '1': true, '2': true,
javascript
{ "resource": "" }
q28318
train
function (text) { if (text.charAt(0) === '[') { switch (text.charAt(text.length - 1)) { case ']': return text; case '"': return text + ']'; case ',': return text.substring(0, text.length - 1) ...
javascript
{ "resource": "" }
q28319
train
function (text) { text = text.replace(new RegExp('</([^d])','g'), '</disabled $1'); text = text.replace(new RegExp('</(\S{2,})','g'), '</disabled $1'); text = text.replace(new RegExp('<([^d/]\W*?)','g'), '<disabled $1');
javascript
{ "resource": "" }
q28320
isNativeFunction
train
function isNativeFunction(f) { if ((typeof f) !== 'function') { return false; } var exp =
javascript
{ "resource": "" }
q28321
PassThrough
train
function PassThrough() { return { buf: '', write: function(b) { this.buf += b; }, end: function(b) {
javascript
{ "resource": "" }
q28322
lineInt
train
function lineInt(l1,l2,precision){ precision = precision || 0; var i = [0,0]; // point var a1, b1, c1, a2, b2, c2, det; // scalars a1 = l1[1][1] - l1[0][1]; b1 = l1[0][0] - l1[1][0]; c1 = a1 * l1[0][0] + b1 * l1[0][1]; a2 = l2[1][1] - l2[0][1]; b2 = l2[0][0] - l2[1][0]; c2 = a2 * l2[...
javascript
{ "resource": "" }
q28323
lineSegmentsIntersect
train
function lineSegmentsIntersect(p1, p2, q1, q2){ var dx = p2[0] - p1[0]; var dy = p2[1] - p1[1]; var da = q2[0] - q1[0]; var db = q2[1] - q1[1]; // segments are parallel if((da*dy
javascript
{ "resource": "" }
q28324
triangleArea
train
function triangleArea(a,b,c){ return (((b[0]
javascript
{ "resource": "" }
q28325
collinear
train
function collinear(a,b,c,thresholdAngle) { if(!thresholdAngle){ return triangleArea(a, b, c) === 0; } else { var ab = tmpPoint1, bc = tmpPoint2; ab[0] = b[0]-a[0]; ab[1] = b[1]-a[1]; bc[0] = c[0]-b[0]; bc[1] = c[1]-b[1]; var dot =
javascript
{ "resource": "" }
q28326
polygonAt
train
function polygonAt(polygon, i){ var s = polygon.length;
javascript
{ "resource": "" }
q28327
polygonAppend
train
function polygonAppend(polygon, poly, from, to){ for(var i=from; i<to; i++){
javascript
{ "resource": "" }
q28328
polygonMakeCCW
train
function polygonMakeCCW(polygon){ var br = 0, v = polygon; // find bottom right point for (var i = 1; i < polygon.length; ++i) { if (v[i][1] < v[br][1] || (v[i][1] === v[br][1] && v[i][0] > v[br][0])) { br = i; } }
javascript
{ "resource": "" }
q28329
polygonReverse
train
function polygonReverse(polygon){ var tmp = []; var N = polygon.length; for(var
javascript
{ "resource": "" }
q28330
polygonIsReflex
train
function polygonIsReflex(polygon, i){ return isRight(polygonAt(polygon,
javascript
{ "resource": "" }
q28331
polygonCopy
train
function polygonCopy(polygon, i,j,targetPoly){ var p = targetPoly || []; polygonClear(p); if (i < j) { // Insert all vertices from i to j for(var k=i; k<=j; k++){ p.push(polygon[k]);
javascript
{ "resource": "" }
q28332
polygonDecomp
train
function polygonDecomp(polygon){ var edges = polygonGetCutEdges(polygon);
javascript
{ "resource": "" }
q28333
polygonIsSimple
train
function polygonIsSimple(polygon){ var path = polygon, i; // Check for(i=0; i<path.length-1; i++){ for(var j=0; j<i-1; j++){ if(lineSegmentsIntersect(path[i], path[i+1], path[j], path[j+1] )){
javascript
{ "resource": "" }
q28334
polygonRemoveCollinearPoints
train
function polygonRemoveCollinearPoints(polygon, precision){ var num = 0; for(var i=polygon.length-1; polygon.length>3 && i>=0; --i){ if(collinear(polygonAt(polygon, i-1),polygonAt(polygon,
javascript
{ "resource": "" }
q28335
polygonRemoveDuplicatePoints
train
function polygonRemoveDuplicatePoints(polygon, precision){ for(var i=polygon.length-1; i>=1; --i){ var pi = polygon[i]; for(var j=i-1; j>=0; --j){
javascript
{ "resource": "" }
q28336
scalar_eq
train
function scalar_eq(a,b,precision){ precision
javascript
{ "resource": "" }
q28337
points_eq
train
function points_eq(a,b,precision){ return scalar_eq(a[0],b[0],precision) &&
javascript
{ "resource": "" }
q28338
serialize
train
function serialize(model) { var data = model.toJSON(); Object.keys(data).forEach(function serializeRecur(key) { var value = data[key];
javascript
{ "resource": "" }
q28339
listen
train
function listen(model, listener) { model.on('change', listener); model.values().forEach(function listenRecur(value) { var isCollection = value && value._byId; if (!isCollection) { return;
javascript
{ "resource": "" }
q28340
listenCollection
train
function listenCollection(collection, listener) { collection.forEach(function listenModel(model) { listen(model, listener); });
javascript
{ "resource": "" }
q28341
parseBabelThing
train
function parseBabelThing(babelThing) { assert_usage([String, Array].includes(babelThing.constructor)); let name; let options; if( babelThing.constructor === Array ) { name = babelThing[0]; options = babelThing[1]; } else {
javascript
{ "resource": "" }
q28342
applyViewWrappers
train
function applyViewWrappers({reactElement, initialProps, viewWrappers=[]}) { viewWrappers
javascript
{ "resource": "" }
q28343
assemble_modifiers
train
function assemble_modifiers(modifier_name, configParts) { const assert_usage = require('reassert/usage'); // `configParts` holds all globalConfig parts // `config` holds a webpack config let supra_modifier = ({config}) => config; // We assemble all `configParts`'s config modifiers into one `supra_...
javascript
{ "resource": "" }
q28344
StreamFormatter
train
function StreamFormatter(loggerManager, options) { if (!(this instanceof StreamFormatter)) { return new StreamFormatter(loggerManager, options); } stream.Readable.call(this, options); this._buffer = []; this._pushable = false; this._ended = false;
javascript
{ "resource": "" }
q28345
logReadableStream
train
function logReadableStream(stream) { var encoding = "utf8"; stream.setEncoding(encoding);
javascript
{ "resource": "" }
q28346
logWriteableStream
train
function logWriteableStream(stream, colorFunction) { var write = stream.write; // The third parameter, callback, will be passed implicitely using arguments stream.write = function (chunk, encoding) { // Write to STDOUT right away
javascript
{ "resource": "" }
q28347
getLogDirectoryElements
train
function getLogDirectoryElements(settings) { var elements, platform = process.platform; if (settings.logRoot) { elements = [settings.logRoot, settings.module]; } else if (platform === "darwin") { elements = [process.env.HOME, "Library", "Logs", settings.vendo...
javascript
{ "resource": "" }
q28348
extractStyleInfo
train
function extractStyleInfo(psd/*, opts*/) { var SON = {}; var layers = psd.layers; _classnames = []; _psd = psd; SON.layers = []; layers.forEach(function (layer) { var s = extractLayerStyleInfo(layer);
javascript
{ "resource": "" }
q28349
train
function (pixmapWidth, pixmapHeight) { // Find out if the mask extends beyond the visible pixels var paddingWanted; ["top", "left", "right", "bottom"].forEach(function (key) { if (paddedInputBounds[key] !== visibleInputBounds[key]) { ...
javascript
{ "resource": "" }
q28350
Client
train
function Client (args, options) { // Ensure Client instantiated with 'new' if (!(this instanceof Client)) { return new Client(args, options); } var servers = [] , weights = {} , regular = 'localhost:11211' , key; // Parse down the connection arguments switch (Object.prototype.toString.call...
javascript
{ "resource": "" }
q28351
stats
train
function stats(resultSet) { var response = {}; if (resultSetIsEmpty(resultSet)) return response; // add references to the retrieved server response.server = this.serverAddress; //
javascript
{ "resource": "" }
q28352
handle
train
function handle(err, results) { if (err) { errors.push(err); } // add all responses to the array (Array.isArray(results) ? results : [results]).forEach(function each(value) { if (value && memcached.namespace.length) { var ns_key = Object.keys(value)[0] , ne...
javascript
{ "resource": "" }
q28353
handle
train
function handle(err, results) { if (err) { errors = errors || []; errors.push(err); } if (results) responses = responses.concat(results); // multi calls should ALWAYS return an array!
javascript
{ "resource": "" }
q28354
updateUserProfileWithToken
train
function updateUserProfileWithToken(messagingToken) { const currentUserUid = firebase.auth().currentUser && firebase.auth().currentUser.uid if (!currentUserUid) { return Promise.resolve();
javascript
{ "resource": "" }
q28355
getMessagingToken
train
function getMessagingToken() { return firebase .messaging() .getToken() .catch(err =>
javascript
{ "resource": "" }
q28356
initStackdriverErrorReporter
train
function initStackdriverErrorReporter() { if (typeof window.StackdriverErrorReporter === 'function') { window.addEventListener('DOMContentLoaded', () => { const errorHandler = new window.StackdriverErrorReporter() errorHandler.start({
javascript
{ "resource": "" }
q28357
initGA
train
function initGA() { if (analyticsTrackingId) { ReactGA.initialize(analyticsTrackingId) ReactGA.set({
javascript
{ "resource": "" }
q28358
setGAUser
train
function setGAUser(auth) { if (auth && auth.uid) {
javascript
{ "resource": "" }
q28359
MediaRecorder
train
function MediaRecorder (stream) { /** * The `MediaStream` passed into the constructor. * @type {MediaStream} */ this.stream = stream /** * The current state of recording process. * @type {"inactive"|"recording"|"paused"} */ this.state = 'inactive' this.em = document.createDocumentFragment(...
javascript
{ "resource": "" }
q28360
start
train
function start (timeslice) { if (this.state !== 'inactive') { return this.em.dispatchEvent(error('start')) } this.state = 'recording' if (!context) { context = new AudioContext() } this.clone = this.stream.clone() var input = context.createMediaStreamSource(this.clone) if ...
javascript
{ "resource": "" }
q28361
stop
train
function stop () { if (this.state === 'inactive') { return this.em.dispatchEvent(error('stop')) } this.requestData() this.state =
javascript
{ "resource": "" }
q28362
balance
train
function balance() { binance.balance((error, balances) => { if ( error ) console.error(error); let btc = 0.00; for ( let asset in balances ) { let obj = balances[asset]; obj.available = parseFloat(obj.available); //if ( !obj.available ) continue; obj.onOrder = parseFloat(obj.onOrder); obj.btcValue...
javascript
{ "resource": "" }
q28363
getAllPropertyDescriptors
train
function getAllPropertyDescriptors(object) { if (object === Object.prototype) { return {}; } else
javascript
{ "resource": "" }
q28364
toNodeStream
train
function toNodeStream (renderer) { let sourceIsReady = true; const read = () => { // If source is not ready, defer any reads until the promise resolves. if (!sourceIsReady) { return false; } sourceIsReady = false; const pull = pullBatch(renderer, stream);
javascript
{ "resource": "" }
q28365
evalComponent
train
function evalComponent (seq, node, context) { const Component = node.type; const componentContext = getContext(Component, context); const instance = constructComponent(Component, node.props, componentContext);
javascript
{ "resource": "" }
q28366
traverse
train
function traverse ({ seq, node, context, numChildren, parent }) { if (node === undefined || node === true) { return; } if (node === false) { if (parent && isFunction(parent.type)) { emitEmpty(seq); return; } else { return; } } if (node === null) { emitEmpty(seq); re...
javascript
{ "resource": "" }
q28367
syncSetState
train
function syncSetState (newState) { // Mutation is faster and should be safe here. this.state = assign( this.state,
javascript
{ "resource": "" }
q28368
toPromise
train
function toPromise (renderer) { // this.sequence, this.batchSize, this.dataReactAttrs const buffer = { value: [], push (segment) { this.value.push(segment); } }; return new Promise((resolve, reject) => setImmediate( asyncBatch, renderer, buffer,
javascript
{ "resource": "" }
q28369
getChildContext
train
function getChildContext (componentPrototype, instance, context) { if (componentPrototype.childContextTypes) {
javascript
{ "resource": "" }
q28370
getContext
train
function getContext (componentPrototype, context) { if (componentPrototype.contextTypes) { const contextTypes = componentPrototype.contextTypes; return keys(context).reduce(
javascript
{ "resource": "" }
q28371
processErrors
train
function processErrors (errors, transformers) { const transform = (error, transformer) => transformer(error);
javascript
{ "resource": "" }
q28372
format
train
function format(errors, type) { return errors .filter(isDefaultError) .reduce((accum, error) => (
javascript
{ "resource": "" }
q28373
formatErrors
train
function formatErrors(errors, formatters, errorType) { const format = (formatter) => formatter(errors, errorType) || []; const flatten = (accum,
javascript
{ "resource": "" }
q28374
doReveal
train
function doReveal(el) { var orig = el.getAttribute('src') || false; el.addEventListener('error', function handler(e) { // on error put back the original image if available (usually a placeholder) console.log('error loading image', e); if (orig) {
javascript
{ "resource": "" }
q28375
reveal
train
function reveal(el) { if (el.hasChildNodes()) { // dealing with a container try and find children var els = el.querySelectorAll('[data-src], [data-bkg]'); var elsl = els.length; if (elsl === 0) { // node has children, but none have the attributes, so reveal // t...
javascript
{ "resource": "" }
q28376
init
train
function init() { // find all elements with the class "appear" var els = document.getElementsByClassName('appear'); var elsl = els.length; // put html elements into an array object to work with for (var i = 0; i < elsl; i += 1) {
javascript
{ "resource": "" }
q28377
debounce
train
function debounce(fn, delay) { return function () { var self = this, args = arguments; clearTimeout(timer); console.log('debounce()');
javascript
{ "resource": "" }
q28378
checkAppear
train
function checkAppear() { if(scroll.delta < opts.delta.speed) { if(!deltaSet) { deltaSet = true; doCheckAppear(); setTimeout(function(){ deltaSet = false;
javascript
{ "resource": "" }
q28379
poly2path
train
function poly2path(polygon) { var pos = polygon.pos; var points = polygon.calcPoints; var result = 'M' + pos.x + ' ' + pos.y; result += 'M' + (pos.x + points[0].x) + ' ' + (pos.y + points[0].y); for (var i = 1; i <
javascript
{ "resource": "" }
q28380
moveDrag
train
function moveDrag(entity, world) { return function (dx, dy) { // This position updating is fairly naive - it lets objects
javascript
{ "resource": "" }
q28381
train
function () { if (this.data instanceof SAT.Circle) { this.displayAttrs.cx = this.data.pos.x; this.displayAttrs.cy = this.data.pos.y; this.displayAttrs.r = this.data.r; } else {
javascript
{ "resource": "" }
q28382
starToIndex
train
function starToIndex (pairs, data, i, out) { if (!data) { return [] } i = i || 0 let curr = pairs[i++] const next = pairs[i] /** * When out is not defined, then start * with the current node */ if (!out) { out = [curr] curr = '' } /** * Keep on adding to the out array. The ...
javascript
{ "resource": "" }
q28383
onRejected
train
function onRejected (error) { return { fullFilled: false, rejected: true,
javascript
{ "resource": "" }
q28384
pSeries
train
function pSeries (iterable, bail) { const result = [] const iterableLength = iterable.length function noop (index, bail) { /** * End of promises */ if (index >= iterableLength) { return Promise.resolve(result) } return iterable[index] .then((output) => { result.push...
javascript
{ "resource": "" }
q28385
start
train
async function start () { let exitCode = 0 const port = process.env.PORT || 3000 console.log(chalk`{magenta creating app bundle}`) /** * Creating rollup bundle by bundling `test/qunit/index.js` file. */ const bundle = await rollup.rollup({ input: path.join(__dirname, '../test', 'qunit', 'index'), ...
javascript
{ "resource": "" }
q28386
setConfig
train
function setConfig (options) { Object.keys(options).forEach((option) => { if (config[option] !==
javascript
{ "resource": "" }
q28387
validationFn
train
function validationFn (validations, {name, args}, field, data, messages, formatter) { return new PLazy((resolve, reject) => { const camelizedName = snakeToCamelCase(name) const validation = validations[camelizedName] if (typeof (validation) !== 'function') { const error = new Error(`${camelizedName...
javascript
{ "resource": "" }
q28388
getValidationsStack
train
function getValidationsStack (validations, fields, data, messages, formatter) { return Object .keys(fields) .reduce((flatValidations, field) => { fields[field].map((rule) => {
javascript
{ "resource": "" }
q28389
validate
train
function validate (validations, bail, data, fields, messages, formatter) { return new Promise((resolve, reject) => { messages = messages || {} /** * This is expanded form of fields and rules * applied on them */ const parsedFields = parse(fields, data) /** * A flat validations st...
javascript
{ "resource": "" }
q28390
sanitizeField
train
function sanitizeField (sanitizations, value, rules) { let result = value rules.forEach((rule) => { const ruleFn = snakeToCamelCase(rule.name) if (typeof (sanitizations[ruleFn]) !== 'function') { throw new
javascript
{ "resource": "" }
q28391
getFiles
train
function getFiles (location, filterFn) { return new Promise((resolve, reject) => { const files = [] klaw(location) .on('data', (item) => { if (!item.stats.isDirectory() && filterFn(item)) {
javascript
{ "resource": "" }
q28392
readFiles
train
async function readFiles (locations) { return Promise.all(locations.map((location) => {
javascript
{ "resource": "" }
q28393
extractComments
train
function extractComments (contents) { let context = 'idle' const lines = [] contents.split('\n').forEach((line) => { if (line.trim() === '/**') { context = 'in' return } if (line.trim() === '*/') { context = 'out'
javascript
{ "resource": "" }
q28394
writeDocs
train
async function writeDocs (basePath, nodes) { Promise.all(nodes.map((node) => { const location
javascript
{ "resource": "" }
q28395
srcToDocs
train
async function srcToDocs (dir) { const location = path.join(srcPath, dir) const srcFiles = await getFiles(location, (item) => item.path.endsWith('.js') && !item.path.endsWith('index.js')) const filesContents = await readFiles(srcFiles) const
javascript
{ "resource": "" }
q28396
parseRules
train
function parseRules (fields, data) { data = data || {} return Object.keys(fields).reduce((result, field) => { let rules = fields[field] /** * Strings are passed to haye for further processing * and if rules are not an array or a string, then * we should blow. */ if (typeof (rules) ...
javascript
{ "resource": "" }
q28397
train
function (route, body, method = 'post') { return got(`https://saucelabs.com/rest/v1/${process.env.SAUCE_USERNAME}/${route}`, { method,
javascript
{ "resource": "" }
q28398
getMessage
train
function getMessage (messages, field, validation, args) { /** * Since we allow array expression as `*`, we want all index of the * current field to be replaced with `.*`, so that we get the * right message. */ const originalField = field.replace(/\.\d/g, '.*') const camelizedValidation = snakeToCamelC...
javascript
{ "resource": "" }
q28399
train
function(bytes) { bytes = bytes || 2; var max = Math.pow(16, bytes) - 1; var css = [ "#", pad(Math.round(this.red * max).toString(16).toUpperCase(), bytes),
javascript
{ "resource": "" }