_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q20600
matchAt
train
function matchAt(content, index, match) { return content.substring(index, index + match.length) === match; }
javascript
{ "resource": "" }
q20601
replaceAt
train
function replaceAt(content, index, oldString, newString) { logger.debug(`Replacing ${oldString} with ${newString} at index ${index}`); return ( content.substr(0, index) + newString + content.substr(index + oldString.length) ); }
javascript
{ "resource": "" }
q20602
getFileList
train
function getFileList(branchName = config.baseBranch) { logger.debug(`getFileList(${branchName})`); return config.storage.getFileList(branchName); }
javascript
{ "resource": "" }
q20603
massageConfig
train
function massageConfig(config) { if (!allowedStrings) { allowedStrings = []; options.forEach(option => { if (option.allowString) { allowedStrings.push(option.name); } }); } const massagedConfig = clone(config); for (const [key, val] of Object.entries(config)) { if (allowedStrings.includes(key) && is.string(val)) { massagedConfig[key] = [val]; } else if (key === 'npmToken' && val && val.length < 50) { massagedConfig.npmrc = `//registry.npmjs.org/:_authToken=${val}\n`; delete massagedConfig.npmToken; } else if (is.array(val)) { massagedConfig[key] = []; val.forEach(item => { if (is.object(item)) { massagedConfig[key].push(massageConfig(item)); } else { massagedConfig[key].push(item); } }); } else if (is.object(val) && key !== 'encrypted') { massagedConfig[key] = massageConfig(val); } } if (is.nonEmptyArray(massagedConfig.packageRules)) { const newRules = []; const updateTypes = [ 'major', 'minor', 'patch', 'pin', 'digest', 'lockFileMaintenance', 'rollback', ]; for (const rule of massagedConfig.packageRules) { newRules.push(rule); for (const [key, val] of Object.entries(rule)) { if (updateTypes.includes(key)) { const newRule = clone(rule); newRule.updateTypes = rule.updateTypes || []; newRule.updateTypes.push(key); Object.assign(newRule, val); newRules.push(newRule); } } } for (const rule of newRules) { updateTypes.forEach(updateType => { delete rule[updateType]; }); } massagedConfig.packageRules = newRules; } return massagedConfig; }
javascript
{ "resource": "" }
q20604
poetry2npm
train
function poetry2npm(input) { const versions = input .split(',') .map(str => str.trim()) .filter(notEmpty); return versions.join(' '); }
javascript
{ "resource": "" }
q20605
initRepo
train
async function initRepo({ repository, endpoint, localDir }) { logger.debug(`initRepo("${repository}")`); const opts = hostRules.find({ platform: 'bitbucket' }, { endpoint }); // istanbul ignore next if (!(opts.username && opts.password)) { throw new Error( `No username/password found for Bitbucket repository ${repository}` ); } hostRules.update({ ...opts, platform: 'bitbucket', default: true }); api.reset(); config = {}; // TODO: get in touch with @rarkins about lifting up the caching into the app layer config.repository = repository; const platformConfig = {}; // Always gitFs const url = GitStorage.getUrl({ gitFs: 'https', auth: `${opts.username}:${opts.password}`, hostname: 'bitbucket.org', repository, }); config.storage = new GitStorage(); await config.storage.initRepo({ ...config, localDir, url, }); try { const info = utils.repoInfoTransformer( (await api.get(`/2.0/repositories/${repository}`)).body ); platformConfig.privateRepo = info.privateRepo; platformConfig.isFork = info.isFork; platformConfig.repoFullName = info.repoFullName; config.owner = info.owner; logger.debug(`${repository} owner = ${config.owner}`); config.defaultBranch = info.mainbranch; config.baseBranch = config.defaultBranch; config.mergeMethod = info.mergeMethod; } catch (err) /* istanbul ignore next */ { if (err.statusCode === 404) { throw new Error('not-found'); } logger.info({ err }, 'Unknown Bitbucket initRepo error'); throw err; } delete config.prList; delete config.fileList; await Promise.all([getPrList(), getFileList()]); return platformConfig; }
javascript
{ "resource": "" }
q20606
getBranchCommit
train
async function getBranchCommit(branchName) { try { const branch = (await api.get( `/2.0/repositories/${config.repository}/refs/branches/${branchName}` )).body; return branch.target.hash; } catch (err) /* istanbul ignore next */ { logger.debug({ err }, `getBranchCommit('${branchName}') failed'`); return null; } }
javascript
{ "resource": "" }
q20607
removeMultiLineComments
train
function removeMultiLineComments(content) { const beginRegExp = /(^|\n)=begin\s/; const endRegExp = /(^|\n)=end\s/; let newContent = content; let i = newContent.search(beginRegExp); let j = newContent.search(endRegExp); while (i !== -1 && j !== -1) { if (newContent[i] === '\n') { i += 1; } if (newContent[j] === '\n') { j += 1; } j += '=end'.length; newContent = newContent.substring(0, i) + newContent.substring(j); i = newContent.search(beginRegExp); j = newContent.search(endRegExp); } return newContent; }
javascript
{ "resource": "" }
q20608
getFile
train
async function getFile(repoId, repository, filePath, branchName) { logger.trace(`getFile(filePath=${filePath}, branchName=${branchName})`); const azureApiGit = await azureApi.gitApi(); const item = await azureApiGit.getItemText( repoId, filePath, null, null, 0, // because we look for 1 file false, false, true, { versionType: 0, // branch versionOptions: 0, version: getBranchNameWithoutRefsheadsPrefix(branchName), } ); if (item && item.readable) { const fileContent = await streamToString(item); try { const jTmp = JSON.parse(fileContent); if (jTmp.typeKey === 'GitItemNotFoundException') { // file not found return null; } if (jTmp.typeKey === 'GitUnresolvableToCommitException') { // branch not found return null; } } catch (error) { // it 's not a JSON, so I send the content directly with the line under } return fileContent; } return null; // no file found }
javascript
{ "resource": "" }
q20609
maxSatisfyingVersion
train
function maxSatisfyingVersion(versions, range) { return versions.find(v => equals(v, range)) || null; }
javascript
{ "resource": "" }
q20610
Pathformer
train
function Pathformer(element) { // Test params if (typeof element === 'undefined') { throw new Error('Pathformer [constructor]: "element" parameter is required'); } // Set the element if (element.constructor === String) { element = document.getElementById(element); if (!element) { throw new Error('Pathformer [constructor]: "element" parameter is not related to an existing ID'); } } if (element instanceof window.SVGElement || element instanceof window.SVGGElement || /^svg$/i.test(element.nodeName)) { this.el = element; } else { throw new Error('Pathformer [constructor]: "element" parameter must be a string or a SVGelement'); } // Start this.scan(element); }
javascript
{ "resource": "" }
q20611
Vivus
train
function Vivus(element, options, callback) { setupEnv(); // Setup this.isReady = false; this.setElement(element, options); this.setOptions(options); this.setCallback(callback); if (this.isReady) { this.init(); } }
javascript
{ "resource": "" }
q20612
record_data
train
function record_data(e) { var lock = LockService.getDocumentLock(); lock.waitLock(30000); // hold off up to 30 sec to avoid concurrent writing try { Logger.log(JSON.stringify(e)); // log the POST data in case we need to debug it // select the 'responses' sheet by default var doc = SpreadsheetApp.getActiveSpreadsheet(); var sheetName = e.parameters.formGoogleSheetName || "responses"; var sheet = doc.getSheetByName(sheetName); var oldHeader = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]; var newHeader = oldHeader.slice(); var fieldsFromForm = getDataColumns(e.parameters); var row = [new Date()]; // first element in the row should always be a timestamp // loop through the header columns for (var i = 1; i < oldHeader.length; i++) { // start at 1 to avoid Timestamp column var field = oldHeader[i]; var output = getFieldFromData(field, e.parameters); row.push(output); // mark as stored by removing from form fields var formIndex = fieldsFromForm.indexOf(field); if (formIndex > -1) { fieldsFromForm.splice(formIndex, 1); } } // set any new fields in our form for (var i = 0; i < fieldsFromForm.length; i++) { var field = fieldsFromForm[i]; var output = getFieldFromData(field, e.parameters); row.push(output); newHeader.push(field); } // more efficient to set values as [][] array than individually var nextRow = sheet.getLastRow() + 1; // get next row sheet.getRange(nextRow, 1, 1, row.length).setValues([row]); // update header row with any new data if (newHeader.length > oldHeader.length) { sheet.getRange(1, 1, 1, newHeader.length).setValues([newHeader]); } } catch(error) { Logger.log(error); } finally { lock.releaseLock(); return; } }
javascript
{ "resource": "" }
q20613
getFormData
train
function getFormData(form) { var elements = form.elements; var fields = Object.keys(elements).filter(function(k) { return (elements[k].name !== "honeypot"); }).map(function(k) { if(elements[k].name !== undefined) { return elements[k].name; // special case for Edge's html collection }else if(elements[k].length > 0){ return elements[k].item(0).name; } }).filter(function(item, pos, self) { return self.indexOf(item) == pos && item; }); var formData = {}; fields.forEach(function(name){ var element = elements[name]; // singular form elements just have one value formData[name] = element.value; // when our element has multiple items, get their values if (element.length) { var data = []; for (var i = 0; i < element.length; i++) { var item = element.item(i); if (item.checked || item.selected) { data.push(item.value); } } formData[name] = data.join(', '); } }); // add form-specific values into the data formData.formDataNameOrder = JSON.stringify(fields); formData.formGoogleSheetName = form.dataset.sheet || "responses"; // default sheet name formData.formGoogleSendEmail = form.dataset.email || ""; // no email by default console.log(formData); return formData; }
javascript
{ "resource": "" }
q20614
resolve
train
function resolve (queries, context) { if (Array.isArray(queries)) { queries = flatten(queries.map(parse)) } else { queries = parse(queries) } return queries.reduce(function (result, query, index) { var selection = query.queryString var isExclude = selection.indexOf('not ') === 0 if (isExclude) { if (index === 0) { throw new BrowserslistError( 'Write any browsers query (for instance, `defaults`) ' + 'before `' + selection + '`') } selection = selection.slice(4) } for (var i = 0; i < QUERIES.length; i++) { var type = QUERIES[i] var match = selection.match(type.regexp) if (match) { var args = [context].concat(match.slice(1)) var array = type.select.apply(browserslist, args).map(function (j) { var parts = j.split(' ') if (parts[1] === '0') { return parts[0] + ' ' + byName(parts[0]).versions[0] } else { return j } }) switch (query.type) { case QUERY_AND: if (isExclude) { return result.filter(function (j) { // remove result items that are in array // (the relative complement of array in result) return array.indexOf(j) === -1 }) } else { return result.filter(function (j) { // remove result items not in array // (intersect of result and array) return array.indexOf(j) !== -1 }) } case QUERY_OR: default: if (isExclude) { var filter = { } array.forEach(function (j) { filter[j] = true }) return result.filter(function (j) { return !filter[j] }) } // union of result and array return result.concat(array) } } } throw unknownQuery(selection) }, []) }
javascript
{ "resource": "" }
q20615
browserslist
train
function browserslist (queries, opts) { if (typeof opts === 'undefined') opts = { } if (typeof opts.path === 'undefined') { opts.path = path.resolve ? path.resolve('.') : '.' } if (typeof queries === 'undefined' || queries === null) { var config = browserslist.loadConfig(opts) if (config) { queries = config } else { queries = browserslist.defaults } } if (!(typeof queries === 'string' || Array.isArray(queries))) { throw new BrowserslistError( 'Browser queries must be an array or string. Got ' + typeof queries + '.') } var context = { ignoreUnknownVersions: opts.ignoreUnknownVersions, dangerousExtend: opts.dangerousExtend } env.oldDataWarning(browserslist.data) var stats = env.getStat(opts, browserslist.data) if (stats) { context.customUsage = { } for (var browser in stats) { fillUsage(context.customUsage, browser, stats[browser]) } } var result = resolve(queries, context).sort(function (name1, name2) { name1 = name1.split(' ') name2 = name2.split(' ') if (name1[0] === name2[0]) { if (FLOAT_RANGE.test(name1[1]) && FLOAT_RANGE.test(name2[1])) { return parseFloat(name2[1]) - parseFloat(name1[1]) } else { return compare(name2[1], name1[1]) } } else { return compare(name1[0], name2[0]) } }) return uniq(result) }
javascript
{ "resource": "" }
q20616
doMatch
train
function doMatch (string, qs) { var or = /^(?:,\s*|\s+OR\s+)(.*)/i var and = /^\s+AND\s+(.*)/i return find(string, function (parsed, n, max) { if (and.test(parsed)) { qs.unshift({ type: QUERY_AND, queryString: parsed.match(and)[1] }) return true } else if (or.test(parsed)) { qs.unshift({ type: QUERY_OR, queryString: parsed.match(or)[1] }) return true } else if (n === max) { qs.unshift({ type: QUERY_OR, queryString: parsed.trim() }) return true } return false }) }
javascript
{ "resource": "" }
q20617
makeDataset
train
function makeDataset(arr, colstats) { var labelix = parseInt($("#labelix").val()); if(labelix < 0) labelix = D + labelix; // -1 should turn to D-1 var data = []; var labels = []; for(var i=0;i<N;i++) { var arri = arr[i]; // create the input datapoint Vol() var p = arri.slice(0, D-1); var xarr = []; for(var j=0;j<D;j++) { if(j===labelix) continue; // skip! if(colstats[j].numeric) { xarr.push(parseFloat(arri[j])); } else { var u = colstats[j].uniques; var ix = u.indexOf(arri[j]); // turn into 1ofk encoding for(var q=0;q<u.length;q++) { if(q === ix) { xarr.push(1.0); } else { xarr.push(0.0); } } } } var x = new convnetjs.Vol(xarr); // process the label (last column) if(colstats[labelix].numeric) { var L = parseFloat(arri[labelix]); // regression } else { var L = colstats[labelix].uniques.indexOf(arri[labelix]); // classification if(L==-1) { console.log('whoa label not found! CRITICAL ERROR, very fishy.'); } } data.push(x); labels.push(L); } var dataset = {}; dataset.data = data; dataset.labels = labels; return dataset; }
javascript
{ "resource": "" }
q20618
train
function() { var b = test_batch; var k = Math.floor(Math.random()*num_samples_per_batch); var n = b*num_samples_per_batch+k; var p = img_data[b].data; var x = new convnetjs.Vol(image_dimension,image_dimension,image_channels,0.0); var W = image_dimension*image_dimension; var j=0; for(var dc=0;dc<image_channels;dc++) { var i=0; for(var xc=0;xc<image_dimension;xc++) { for(var yc=0;yc<image_dimension;yc++) { var ix = ((W * k) + i) * 4 + dc; x.set(yc,xc,dc,p[ix]/255.0-0.5); i++; } } } // distort position and maybe flip var xs = []; if (random_flip || random_position){ for(var k=0;k<6;k++) { var test_variation = x; if(random_position){ var dx = Math.floor(Math.random()*5-2); var dy = Math.floor(Math.random()*5-2); test_variation = convnetjs.augment(test_variation, image_dimension, dx, dy, false); } if(random_flip){ test_variation = convnetjs.augment(test_variation, image_dimension, 0, 0, Math.random()<0.5); } xs.push(test_variation); } }else{ xs.push(x, image_dimension, 0, 0, false); // push an un-augmented copy } // return multiple augmentations, and we will average the network over them // to increase performance return {x:xs, label:labels[n]}; }
javascript
{ "resource": "" }
q20619
train
function() { var num_classes = net.layers[net.layers.length-1].out_depth; document.getElementById('testset_acc').innerHTML = ''; var num_total = 0; var num_correct = 0; // grab a random test image for(num=0;num<4;num++) { var sample = sample_test_instance(); var y = sample.label; // ground truth label // forward prop it through the network var aavg = new convnetjs.Vol(1,1,num_classes,0.0); // ensures we always have a list, regardless if above returns single item or list var xs = [].concat(sample.x); var n = xs.length; for(var i=0;i<n;i++) { var a = net.forward(xs[i]); aavg.addFrom(a); } var preds = []; for(var k=0;k<aavg.w.length;k++) { preds.push({k:k,p:aavg.w[k]}); } preds.sort(function(a,b){return a.p<b.p ? 1:-1;}); var correct = preds[0].k===y; if(correct) num_correct++; num_total++; var div = document.createElement('div'); div.className = 'testdiv'; // draw the image into a canvas draw_activations_COLOR(div, xs[0], 2); // draw Vol into canv // add predictions var probsdiv = document.createElement('div'); var t = ''; for(var k=0;k<3;k++) { var col = preds[k].k===y ? 'rgb(85,187,85)' : 'rgb(187,85,85)'; t += '<div class=\"pp\" style=\"width:' + Math.floor(preds[k].p/n*100) + 'px; background-color:' + col + ';\">' + classes_txt[preds[k].k] + '</div>' } probsdiv.innerHTML = t; probsdiv.className = 'probsdiv'; div.appendChild(probsdiv); // add it into DOM $(div).prependTo($("#testset_vis")).hide().fadeIn('slow').slideDown('slow'); if($(".probsdiv").length>200) { $("#testset_vis > .probsdiv").last().remove(); // pop to keep upper bound of shown items } } testAccWindow.add(num_correct/num_total); $("#testset_acc").text('test accuracy based on last 200 test images: ' + testAccWindow.get_average()); }
javascript
{ "resource": "" }
q20620
train
function(lst, x, y, w, h) { lst.push(new Wall(new Vec(x,y), new Vec(x+w,y))); lst.push(new Wall(new Vec(x+w,y), new Vec(x+w,y+h))); lst.push(new Wall(new Vec(x+w,y+h), new Vec(x,y+h))); lst.push(new Wall(new Vec(x,y+h), new Vec(x,y))); }
javascript
{ "resource": "" }
q20621
train
function() { // positional information this.p = new Vec(50, 50); this.op = this.p; // old position this.angle = 0; // direction facing this.actions = []; this.actions.push([1,1]); this.actions.push([0.8,1]); this.actions.push([1,0.8]); this.actions.push([0.5,0]); this.actions.push([0,0.5]); // properties this.rad = 10; this.eyes = []; for(var k=0;k<9;k++) { this.eyes.push(new Eye((k-3)*0.25)); } // braaain //this.brain = new deepqlearn.Brain(this.eyes.length * 3, this.actions.length); var spec = document.getElementById('qspec').value; eval(spec); this.brain = brain; this.reward_bonus = 0.0; this.digestion_signal = 0.0; // outputs on world this.rot1 = 0.0; // rotation speed of 1st wheel this.rot2 = 0.0; // rotation speed of 2nd wheel this.prevactionix = -1; }
javascript
{ "resource": "" }
q20622
train
function() { var new_defs = []; for(var i=0;i<defs.length;i++) { var def = defs[i]; if(def.type==='softmax' || def.type==='svm') { // add an fc layer here, there is no reason the user should // have to worry about this and we almost always want to new_defs.push({type:'fc', num_neurons: def.num_classes}); } if(def.type==='regression') { // add an fc layer here, there is no reason the user should // have to worry about this and we almost always want to new_defs.push({type:'fc', num_neurons: def.num_neurons}); } if((def.type==='fc' || def.type==='conv') && typeof(def.bias_pref) === 'undefined'){ def.bias_pref = 0.0; if(typeof def.activation !== 'undefined' && def.activation === 'relu') { def.bias_pref = 0.1; // relus like a bit of positive bias to get gradients early // otherwise it's technically possible that a relu unit will never turn on (by chance) // and will never get any gradient and never contribute any computation. Dead relu. } } new_defs.push(def); if(typeof def.activation !== 'undefined') { if(def.activation==='relu') { new_defs.push({type:'relu'}); } else if (def.activation==='sigmoid') { new_defs.push({type:'sigmoid'}); } else if (def.activation==='tanh') { new_defs.push({type:'tanh'}); } else if (def.activation==='maxout') { // create maxout activation, and pass along group size, if provided var gs = def.group_size !== 'undefined' ? def.group_size : 2; new_defs.push({type:'maxout', group_size:gs}); } else { console.log('ERROR unsupported activation ' + def.activation); } } if(typeof def.drop_prob !== 'undefined' && def.type !== 'dropout') { new_defs.push({type:'dropout', drop_prob: def.drop_prob}); } } return new_defs; }
javascript
{ "resource": "" }
q20623
train
function(w) { if(w.length === 0) { return {}; } // ... ;s var maxv = w[0]; var minv = w[0]; var maxi = 0; var mini = 0; var n = w.length; for(var i=1;i<n;i++) { if(w[i] > maxv) { maxv = w[i]; maxi = i; } if(w[i] < minv) { minv = w[i]; mini = i; } } return {maxi: maxi, maxv: maxv, mini: mini, minv: minv, dv:maxv-minv}; }
javascript
{ "resource": "" }
q20624
train
function(lst, probs) { var p = randf(0, 1.0); var cumprob = 0.0; for(var k=0,n=lst.length;k<n;k++) { cumprob += probs[k]; if(p < cumprob) { return lst[k]; } } }
javascript
{ "resource": "" }
q20625
train
function(opt, field_name, default_value) { if(typeof field_name === 'string') { // case of single string return (typeof opt[field_name] !== 'undefined') ? opt[field_name] : default_value; } else { // assume we are given a list of string instead var ret = default_value; for(var i=0;i<field_name.length;i++) { var f = field_name[i]; if (typeof opt[f] !== 'undefined') { ret = opt[f]; // overwrite return value } } return ret; } }
javascript
{ "resource": "" }
q20626
train
function(state0, action0, reward0, state1) { this.state0 = state0; this.action0 = action0; this.reward0 = reward0; this.state1 = state1; }
javascript
{ "resource": "" }
q20627
randi
train
function randi(s, e) { return Math.floor(Math.random()*(e-s) + s); }
javascript
{ "resource": "" }
q20628
randn
train
function randn(mean, variance) { var V1, V2, S; do { var U1 = Math.random(); var U2 = Math.random(); V1 = 2 * U1 - 1; V2 = 2 * U2 - 1; S = V1 * V1 + V2 * V2; } while (S > 1); X = Math.sqrt(-2 * Math.log(S) / S) * V1; X = mean + Math.sqrt(variance) * X; return X; }
javascript
{ "resource": "" }
q20629
train
function(opt) { var opt = opt || {}; // required this.k = opt.k; this.n = opt.n; this.alpha = opt.alpha; this.beta = opt.beta; // computed this.out_sx = opt.in_sx; this.out_sy = opt.in_sy; this.out_depth = opt.in_depth; this.layer_type = 'lrn'; // checks if(this.n%2 === 0) { console.log('WARNING n should be odd for LRN layer'); } }
javascript
{ "resource": "" }
q20630
train
function() { var N = this.data.length; var num_train = Math.floor(this.train_ratio * N); this.folds = []; // flush folds, if any for(var i=0;i<this.num_folds;i++) { var p = randperm(N); this.folds.push({train_ix: p.slice(0, num_train), test_ix: p.slice(num_train, N)}); } }
javascript
{ "resource": "" }
q20631
train
function() { var input_depth = this.data[0].w.length; var num_classes = this.unique_labels.length; // sample network topology and hyperparameters var layer_defs = []; layer_defs.push({type:'input', out_sx:1, out_sy:1, out_depth: input_depth}); var nl = weightedSample([0,1,2,3], [0.2, 0.3, 0.3, 0.2]); // prefer nets with 1,2 hidden layers for(var q=0;q<nl;q++) { var ni = randi(this.neurons_min, this.neurons_max); var act = ['tanh','maxout','relu'][randi(0,3)]; if(randf(0,1)<0.5) { var dp = Math.random(); layer_defs.push({type:'fc', num_neurons: ni, activation: act, drop_prob: dp}); } else { layer_defs.push({type:'fc', num_neurons: ni, activation: act}); } } layer_defs.push({type:'softmax', num_classes: num_classes}); var net = new Net(); net.makeLayers(layer_defs); // sample training hyperparameters var bs = randi(this.batch_size_min, this.batch_size_max); // batch size var l2 = Math.pow(10, randf(this.l2_decay_min, this.l2_decay_max)); // l2 weight decay var lr = Math.pow(10, randf(this.learning_rate_min, this.learning_rate_max)); // learning rate var mom = randf(this.momentum_min, this.momentum_max); // momentum. Lets just use 0.9, works okay usually ;p var tp = randf(0,1); // trainer type var trainer_def; if(tp<0.33) { trainer_def = {method:'adadelta', batch_size:bs, l2_decay:l2}; } else if(tp<0.66) { trainer_def = {method:'adagrad', learning_rate: lr, batch_size:bs, l2_decay:l2}; } else { trainer_def = {method:'sgd', learning_rate: lr, momentum: mom, batch_size:bs, l2_decay:l2}; } var trainer = new Trainer(net, trainer_def); var cand = {}; cand.acc = []; cand.accv = 0; // this will maintained as sum(acc) for convenience cand.layer_defs = layer_defs; cand.trainer_def = trainer_def; cand.net = net; cand.trainer = trainer; return cand; }
javascript
{ "resource": "" }
q20632
train
function() { this.candidates = []; // flush, if any for(var i=0;i<this.num_candidates;i++) { var cand = this.sampleCandidate(); this.candidates.push(cand); } }
javascript
{ "resource": "" }
q20633
train
function(data) { // forward prop the best networks // and accumulate probabilities at last layer into a an output Vol var eval_candidates = []; var nv = 0; if(this.evaluated_candidates.length === 0) { // not sure what to do here, first batch of nets hasnt evaluated yet // lets just predict with current candidates. nv = this.candidates.length; eval_candidates = this.candidates; } else { // forward prop the best networks from evaluated_candidates nv = Math.min(this.ensemble_size, this.evaluated_candidates.length); eval_candidates = this.evaluated_candidates } // forward nets of all candidates and average the predictions var xout, n; for(var j=0;j<nv;j++) { var net = eval_candidates[j].net; var x = net.forward(data); if(j===0) { xout = x; n = x.w.length; } else { // add it on for(var d=0;d<n;d++) { xout.w[d] += x.w[d]; } } } // produce average for(var d=0;d<n;d++) { xout.w[d] /= nv; } return xout; }
javascript
{ "resource": "" }
q20634
reload
train
function reload() { eval($("#layerdef").val()); // refresh buttons var t = ''; for(var i=1;i<net.layers.length-1;i++) { // ignore input and regression layers (first and last) var butid = "button" + i; t += "<input id=\""+butid+"\" value=\"" + net.layers[i].layer_type +"\" type=\"submit\" onclick=\"updateLix("+i+")\" style=\"width:80px; height: 30px; margin:5px;\";>"; } $("#layer_ixes").html(t); $("#button"+lix).css('background-color', '#FFA'); }
javascript
{ "resource": "" }
q20635
hardLock
train
function hardLock(callback) { return self.apos.locks.lock('save-area-' + docId, { waitForSelf: true }, function(err) { if (err) { return callback(err); } hardLocked = true; return callback(null); }); }
javascript
{ "resource": "" }
q20636
advisoryLock
train
function advisoryLock(callback) { if (!(req.htmlPageId && req.user)) { // Some consumers of this API might not participate // in advisory locking. Also, make sure we have a // valid user to minimize the risk of a DOS attack // via nuisance locking return callback(null); } return self.apos.docs.lock(req, docId, req.htmlPageId, callback); }
javascript
{ "resource": "" }
q20637
train
function(eventName, fn) { apos.handlers[eventName] = (apos.handlers[eventName] || []).concat([ fn ]); }
javascript
{ "resource": "" }
q20638
train
function(eventName, fn) { if (!fn) { delete apos.handlers[eventName]; return; } apos.handlers[eventName] = _.filter(apos.handlers[eventName], function(_fn) { return fn !== _fn; }); }
javascript
{ "resource": "" }
q20639
train
function(type, options, alias) { if (_.has(apos.modules, type)) { // Don't double-create singletons on apos.change(), leads to doubled click events etc. return; } var module = apos.create(type, options); apos.modules[type] = module; if (alias) { apos[alias] = module; } }
javascript
{ "resource": "" }
q20640
findSafe
train
function findSafe($element, selector, ignore) { var $self = $element; return $self.find(selector).filter(function() { var $parents = $(this).parents(); var i; for (i = 0; (i < $parents.length); i++) { if ($parents[i] === $self[0]) { return true; } if ($($parents[i]).is(ignore)) { return false; } } }); }
javascript
{ "resource": "" }
q20641
train
function (domElement, styles) { styles = styles || (document.defaultView && document.defaultView.getComputedStyle ? document.defaultView.getComputedStyle(domElement, null) : domElement.currentStyle); var px = document.defaultView && document.defaultView.getComputedStyle ? true : false; var b = { top: (parseFloat(px ? styles.borderTopWidth : $.css(domElement, "borderTopWidth")) || 0), left: (parseFloat(px ? styles.borderLeftWidth : $.css(domElement, "borderLeftWidth")) || 0), bottom: (parseFloat(px ? styles.borderBottomWidth : $.css(domElement, "borderBottomWidth")) || 0), right: (parseFloat(px ? styles.borderRightWidth : $.css(domElement, "borderRightWidth")) || 0) }; return { top: b.top, left: b.left, bottom: b.bottom, right: b.right, vertical: b.top + b.bottom, horizontal: b.left + b.right }; }
javascript
{ "resource": "" }
q20642
findSafe
train
function findSafe($context, selector) { if (arguments.length === 1) { selector = arguments[0]; $context = self.$el; } if (!options.nestGuard) { return $context.find(selector); } return $context.find(selector).not($context.find(options.nestGuard).find(selector)); }
javascript
{ "resource": "" }
q20643
getChildren
train
function getChildren(cb) { const path = self.matchDescendants(page); self.find(req, { path: path }).sort({ path: 1 }).toArray((err, res) => { if (!err) { tree = tree.concat(res); } return cb(err, res); }); }
javascript
{ "resource": "" }
q20644
trashOrUntrashPages
train
function trashOrUntrashPages(cb) { const ids = tree.map(p => p._id); return self.apos.docs.db.update({ _id: { $in: ids } }, action, { multi: true }, (err, res) => { cb(err); }); }
javascript
{ "resource": "" }
q20645
train
function(callback) { var matches = url.match(/(\w+)\.wufoo\.com\/forms\/[\w]+-[\w-]+/); if (!matches) { return setImmediate(callback); } return request(url, function(err, response, body) { if (err) { return callback(err); } var matches = body.match(/"(https?:\/\/\w+\.wufoo\.com\/forms\/\w+)\/"/); if (matches) { url = matches[1]; } return callback(null); }); }
javascript
{ "resource": "" }
q20646
train
function(filter, choice) { var choices = []; for (var i = 0; i < filter.choices.length; i++) { choices.push({ label: filter.choices[i].label, action: filter.name, value: filterValueToChoiceValue(filter.choices[i].value, choice), default: filter.choices[i].value === filter.def }); }; return choices; }
javascript
{ "resource": "" }
q20647
train
function(self, options) { self._id = options._id; self.body = { _id: self._id }; self.beforeShow = function(callback) { self.$el.on('click', '[data-open-changes]', function() { var $toggle = $(this); var $version = $toggle.closest('[data-version]'); var currentId = $version.attr('data-version'); var oldId = $version.attr('data-previous'); var $versionContent = $version.find('[data-changes]'); var noChanges = self.$el.find('[data-no-changes]').attr('data-no-changes'); if ($versionContent.html() !== '') { $versionContent.html(''); } else { self.html('compare', { oldId: oldId, currentId: currentId }, function(html) { if (html && html.trim() === '') { html = noChanges; } $versionContent.html(html); }); } return false; }); self.$el.on('click', '[data-apos-revert]', function() { self.api('revert', { _id: $(this).closest('[data-version]').attr('data-version') }, function(result) { if (result.status !== 'ok') { apos.notify('An error occurred.', { type: 'error', dismiss: true }); return; } self.hide(); return self.options.afterRevert(); } ); return false; }); return callback(null); }; }
javascript
{ "resource": "" }
q20648
train
function(pathname, css, req, next) { if (!self.options.bless) { fs.writeFileSync(pathname, css); return next(); } self.splitWithBless(pathname, css); return next(); }
javascript
{ "resource": "" }
q20649
train
function(list, property) { if (_.isArray(list)) { return _.some(list, function(item) { return _.has(item, property); }); } else { return _.has(list, property); } }
javascript
{ "resource": "" }
q20650
train
function(list, value) { if (_.isArray(list)) { for (var i = 0; i < list.length; i++) { var listItem = list[i]; if (listItem.indexOf(value) === 0) { return true; } } } else { if (list.indexOf(value) === 0) { return true; } } return false; }
javascript
{ "resource": "" }
q20651
train
function(arr, property, value) { return _.find(arr, function(item) { return (item[property] === value); }); }
javascript
{ "resource": "" }
q20652
train
function(arr, property, value) { return _.filter(arr, function(item) { return (item[property] === value); }); }
javascript
{ "resource": "" }
q20653
train
function(arr, property, value) { return _.reject(arr, function(item) { return (item[property] === value); }); }
javascript
{ "resource": "" }
q20654
train
function(array, without, property) { return _.filter(Array.isArray(array) ? array : [], function(item) { return !_.find(without || [], function(other) { if (property) { return _.isEqual(item[property], other); } else { return _.isEqual(item, other); } }); }); }
javascript
{ "resource": "" }
q20655
train
function() { var result = {}; var i; for (i = 0; (i < arguments.length); i++) { if (!arguments[i]) { continue; } result = _.merge(result, arguments[i]); } return result; }
javascript
{ "resource": "" }
q20656
cleanup
train
function cleanup(html) { html = cheerio.load(html); html('[' + ignoreAttr + ']').removeAttr(ignoreAttr); html = html.html(); return html; }
javascript
{ "resource": "" }
q20657
train
function(options) { var pages = []; var fromPage = options.page - 2; if (fromPage < 2) { fromPage = 2; } for (var page = fromPage; (page < (fromPage + options.shown)); page++) { pages.push(page); } return pages; }
javascript
{ "resource": "" }
q20658
train
function(msg) { // eslint-disable-next-line no-console if (console.debug) { // eslint-disable-next-line no-console console.debug.apply(console, arguments); } else { // eslint-disable-next-line no-console console.log.apply(console, arguments); } }
javascript
{ "resource": "" }
q20659
train
function(callback) { async.forEachSeries(file.crops || [], function(crop, callback) { console.log('RECROPPING'); var originalFile = '/attachments/' + file._id + '-' + file.name + '.' + crop.left + '.' + crop.top + '.' + crop.width + '.' + crop.height + '.' + file.extension; console.log("Cropping " + tempFile + " to " + originalFile); return self.uploadfs.copyImageIn(tempFile, originalFile, { crop: crop }, function(err) { if (err) { console.error('WARNING: problem copying image back into uploadfs:'); console.error(err); return fileCallback(null); } return callback(null); }); }, callback); }
javascript
{ "resource": "" }
q20660
train
function() { return $(apos.modalSupport.stack.length ? apos.modalSupport.stack[apos.modalSupport.stack.length - 1] : 'body'); }
javascript
{ "resource": "" }
q20661
baseGet
train
function baseGet(object, path, pathKey) { if (object == null) { return; } object = toObject(object); if (pathKey !== undefined && pathKey in object) { path = [pathKey]; } var index = 0, length = path.length; while (object != null && index < length) { object = toObject(object)[path[index++]]; } return (index && index == length) ? object : undefined; }
javascript
{ "resource": "" }
q20662
toIterable
train
function toIterable(value) { if (value == null) { return []; } if (!isArrayLike(value)) { return values(value); } if (lodash.support.unindexedChars && isString(value)) { return value.split(''); } return isObject(value) ? value : Object(value); }
javascript
{ "resource": "" }
q20663
toObject
train
function toObject(value) { if (lodash.support.unindexedChars && isString(value)) { var index = -1, length = value.length, result = Object(value); while (++index < length) { result[index] = value.charAt(index); } return result; } return isObject(value) ? value : Object(value); }
javascript
{ "resource": "" }
q20664
has
train
function has(object, path) { if (object == null) { return false; } var result = hasOwnProperty.call(object, path); if (!result && !isKey(path)) { path = toPath(path); object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); if (object == null) { return false; } path = last(path); result = hasOwnProperty.call(object, path); } return result || (isLength(object.length) && isIndex(path, object.length) && (isArray(object) || isArguments(object) || isString(object))); }
javascript
{ "resource": "" }
q20665
train
function(widget, options) { var manager = self.getWidgetManager(widget.type); if (!manager) { // Not configured in this project self.warnMissingWidgetType(widget.type); return ''; } var partial; if (!manager.options.wrapperTemplate) { partial = _.partial(self.partial, 'widget'); } else { partial = _.partial(manager.partial, manager.options.wrapperTemplate); } return partial({ // The widget minus any properties that don't // absolutely need to be crammed into a JSON // attribute for the editor's benefit. Good filtering // here prevents megabytes of markup. -Tom and Sam dataFiltered: manager.filterForDataAttribute(widget), manager: manager, widget: widget, options: options, output: function() { return manager.output(widget, options); } }); }
javascript
{ "resource": "" }
q20666
train
function(widget, options) { return self.widgetControlGroups(self.apos.templates.contextReq, widget, options); }
javascript
{ "resource": "" }
q20667
train
function(callback) { if (callback) { return body(callback); } else { return Promise.promisify(body)(); } function body(callback) { return self.cacheCollection.remove({ name: name }, callback); } }
javascript
{ "resource": "" }
q20668
clean
train
function clean(nodes) { mark(nodes, []); return prune(nodes); function mark(nodes, ancestors) { _.each(nodes, function(node) { if (node.publish) { node.good = true; _.each(ancestors, function(ancestor) { ancestor.good = true; }); } mark(node.children || [], ancestors.concat([ node ])); }); } function prune(nodes) { var newNodes = []; _.each(nodes, function(node) { node.children = prune(node.children || []); if (node.good) { newNodes.push(node); } }); return newNodes; } }
javascript
{ "resource": "" }
q20669
train
function(self, options) { self.options = options; self.editorName = self.name + '-widgets-editor'; // Opens the editor modal of a widget, unless the widget is contextualOnly, // in which case we simply save the widget and call the save method // Widget can opitonally be set to skipInitialModal which skips the first // edit modal but binds future editing interactions self.edit = function(data, options, save) { if (!data) { data = {}; } if (!data._id) { _.assign(data, apos.schemas.newInstance(self.schema)); } // Only create a modal editor if the schema is not contextual only if (self.options.contextualOnly) { return save(checkOrGenerateId(data), function() {}); } else { if (self.options.skipInitialModal && (!data || !data._id)) { return save(checkOrGenerateId(data), function() {}); } apos.create(self.editorName, { label: self.label, action: self.options.action, schema: self.options.schema, data: data, templateOptions: options, save: save, module: self }); } // Checks for an id or assign a generated one function checkOrGenerateId (data) { data = data || {}; if (!data._id) { data._id = apos.utils.generateId(); } return data; } }; // Area editor calls this to determine whether to apply an empty state // class for the widget self.isEmpty = function($widget) { return false; }; var superGetData = self.getData; self.getData = function($widget) { var data = superGetData($widget); // If the field is contextual and its type has a `contextualConvert` // function, we need to run that when retrieving the widget's data. // Or, if the field has a `contextualIsPresent` method, we can use that // to check whether an editor is actually present for it, bypassing the // need to restrict this feature solely to fields marked contextual // in the schema. _.each(self.schema, function(field) { var type = apos.schemas.fieldTypes[field.type]; if ( (type.contextualIsPresent && type.contextualIsPresent($widget, field) && type.contextualConvert) || (field.contextual && type.contextualConvert) ) { apos.schemas.fieldTypes[field.type].contextualConvert(data, field.name, $widget, field); } }); return data; }; // Start autosaving the area containing the given widget, // then invoke the given function. On failure fn is not invoked. // Invoked by widgets that are edited contextually on the page, // like apostrophe-rich-text, as opposed to widgets edited // via a modal. self.startAutosavingAreaThen = function($widget, fn) { var $area = $widget.closest('[data-apos-area]'); return $area.data('editor').startAutosavingThen(fn); }; }
javascript
{ "resource": "" }
q20670
checkOrGenerateId
train
function checkOrGenerateId (data) { data = data || {}; if (!data._id) { data._id = apos.utils.generateId(); } return data; }
javascript
{ "resource": "" }
q20671
train
function (id, name, isFatal) { this.id = id; this.name = name; this.installed = false; this.metadata = {}; this.isFatal = isFatal || false; }
javascript
{ "resource": "" }
q20672
cleanWww
train
function cleanWww (projectRoot, locations) { var targetDir = path.relative(projectRoot, locations.www); events.emit('verbose', 'Cleaning ' + targetDir); // No source paths are specified, so mergeAndUpdateDir() will clear the target directory. FileUpdater.mergeAndUpdateDir( [], targetDir, { rootDir: projectRoot, all: true }, logFileOp); }
javascript
{ "resource": "" }
q20673
mapLaunchStoryboardResources
train
function mapLaunchStoryboardResources (splashScreens, launchStoryboardImagesDir) { var platformLaunchStoryboardImages = mapLaunchStoryboardContents(splashScreens, launchStoryboardImagesDir); var pathMap = {}; platformLaunchStoryboardImages.forEach(function (item) { if (item.target) { pathMap[item.target] = item.src; } }); return pathMap; }
javascript
{ "resource": "" }
q20674
getLaunchStoryboardImagesDir
train
function getLaunchStoryboardImagesDir (projectRoot, platformProjDir) { var launchStoryboardImagesDir; var xcassetsExists = folderExists(path.join(projectRoot, platformProjDir, 'Images.xcassets/')); if (xcassetsExists) { launchStoryboardImagesDir = path.join(platformProjDir, 'Images.xcassets/LaunchStoryboard.imageset/'); } else { // if we don't have a asset library for images, we can't do the storyboard. launchStoryboardImagesDir = null; } return launchStoryboardImagesDir; }
javascript
{ "resource": "" }
q20675
updateLaunchStoryboardImages
train
function updateLaunchStoryboardImages (cordovaProject, locations) { var splashScreens = cordovaProject.projectConfig.getSplashScreens('ios'); var platformProjDir = path.relative(cordovaProject.root, locations.xcodeCordovaProj); var launchStoryboardImagesDir = getLaunchStoryboardImagesDir(cordovaProject.root, platformProjDir); if (launchStoryboardImagesDir) { var resourceMap = mapLaunchStoryboardResources(splashScreens, launchStoryboardImagesDir); var contentsJSON = getLaunchStoryboardContentsJSON(splashScreens, launchStoryboardImagesDir); events.emit('verbose', 'Updating launch storyboard images at ' + launchStoryboardImagesDir); FileUpdater.updatePaths( resourceMap, { rootDir: cordovaProject.root }, logFileOp); events.emit('verbose', 'Updating Storyboard image set contents.json'); fs.writeFileSync(path.join(cordovaProject.root, launchStoryboardImagesDir, 'Contents.json'), JSON.stringify(contentsJSON, null, 2)); } }
javascript
{ "resource": "" }
q20676
getDefaultSimulatorTarget
train
function getDefaultSimulatorTarget () { return require('./list-emulator-build-targets').run() .then(function (emulators) { var targetEmulator; if (emulators.length > 0) { targetEmulator = emulators[0]; } emulators.forEach(function (emulator) { if (emulator.name.indexOf('iPhone') === 0) { targetEmulator = emulator; } }); return targetEmulator; }); }
javascript
{ "resource": "" }
q20677
findXCodeProjectIn
train
function findXCodeProjectIn (projectPath) { // 'Searching for Xcode project in ' + projectPath); var xcodeProjFiles = shell.ls(projectPath).filter(function (name) { return path.extname(name) === '.xcodeproj'; }); if (xcodeProjFiles.length === 0) { return Q.reject('No Xcode project found in ' + projectPath); } if (xcodeProjFiles.length > 1) { events.emit('warn', 'Found multiple .xcodeproj directories in \n' + projectPath + '\nUsing first one'); } var projectName = path.basename(xcodeProjFiles[0], '.xcodeproj'); return Q.resolve(projectName); }
javascript
{ "resource": "" }
q20678
logWithArgs
train
function logWithArgs(level, args) { args = [level].concat([].slice.call(args)); logger.logLevel.apply(logger, args); }
javascript
{ "resource": "" }
q20679
handleBridgeChange
train
function handleBridgeChange() { if (proxyChanged()) { var commandString = commandQueue.shift(); while(commandString) { var command = JSON.parse(commandString); var callbackId = command[0]; var service = command[1]; var action = command[2]; var actionArgs = command[3]; var callbacks = cordova.callbacks[callbackId] || {}; execProxy(callbacks.success, callbacks.fail, service, action, actionArgs); commandString = commandQueue.shift(); }; return true; } return false; }
javascript
{ "resource": "" }
q20680
cordovaExec
train
function cordovaExec() { var cexec = require('cordova/exec'); var cexec_valid = (typeof cexec.nativeFetchMessages === 'function') && (typeof cexec.nativeEvalAndFetch === 'function') && (typeof cexec.nativeCallback === 'function'); return (cexec_valid && execProxy !== cexec)? cexec : iOSExec; }
javascript
{ "resource": "" }
q20681
requireLocalPkg
train
function requireLocalPkg(fspath, pkgName) { const modulePath = findPkg(fspath, pkgName) if (modulePath) { try { return require(modulePath) } catch (e) { console.warn(`Failed to load ${pkgName} from ${modulePath}. Using bundled`) } } return require(pkgName) }
javascript
{ "resource": "" }
q20682
validateNesting
train
function validateNesting(node) { let queue = [...node.parent.children]; let child; let opener; while (queue.length) { child = queue.shift(); opener = child.openingElement; if (child.type === 'JSXElement' && opener && (opener.name.name === 'input' || opener.name.name === 'textarea')) { return true; } if (child.children) { queue = queue.concat(child.children); } } return false; }
javascript
{ "resource": "" }
q20683
isPlainObject
train
function isPlainObject(value) { return ( isObject(value) && (!value.constructor || value.constructor === Object) && (!value.toString || value.toString === Object.prototype.toString) ); }
javascript
{ "resource": "" }
q20684
pruneGraphs
train
function pruneGraphs(graph, graphOptions) { return currentGraph => { pruneRelatedBranches(graph, currentGraph, graphOptions); if (!graphOptions.isInsertOnly()) { pruneDeletedBranches(graph, currentGraph); } return currentGraph; }; }
javascript
{ "resource": "" }
q20685
mapAfterAllReturn
train
function mapAfterAllReturn(arr, mapper, returnValue) { const results = new Array(arr.length); let containsPromise = false; for (let i = 0, l = arr.length; i < l; ++i) { results[i] = mapper(arr[i]); if (isPromise(results[i])) { containsPromise = true; } } if (containsPromise) { return Promise.all(results).then(() => returnValue); } else { return returnValue; } }
javascript
{ "resource": "" }
q20686
promiseMap
train
function promiseMap(items, mapper, opt) { switch (items.length) { case 0: return mapZero(); case 1: return mapOne(items, mapper); default: return mapMany(items, mapper, opt); } }
javascript
{ "resource": "" }
q20687
initCloneArray
train
function initCloneArray(array) { var length = array.length, result = new array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; }
javascript
{ "resource": "" }
q20688
createInputColumnSelector
train
function createInputColumnSelector(nodes) { return builder => { const selects = new Map(); for (const node of nodes) { const databaseJson = node.obj.$toDatabaseJson(builder); for (const column of Object.keys(databaseJson)) { if (!shouldSelectColumn(column, selects, node)) { continue; } const selection = createManyToManyExtraSelectionIfNeeded(builder, column, node) || createSelection(builder, column, node); selects.set(column, selection); } } const selectArr = Array.from(selects.values()); const idColumn = builder.fullIdColumn(); if (!selectArr.includes(idColumn)) { // Always select the identifer. selectArr.push(idColumn); } builder.select(selectArr); }; }
javascript
{ "resource": "" }
q20689
memoize
train
function memoize(func) { const cache = new Map(); return input => { let output = cache.get(input); if (output === undefined) { output = func(input); cache.set(input, output); } return output; }; }
javascript
{ "resource": "" }
q20690
camelCase
train
function camelCase(str, { upperCase = false } = {}) { if (str.length === 0) { return str; } if (upperCase && isAllUpperCaseSnakeCase(str)) { // Only convert to lower case if the string is all upper // case snake_case. This allowes camelCase strings to go // through without changing. str = str.toLowerCase(); } let out = str[0]; for (let i = 1, l = str.length; i < l; ++i) { const char = str[i]; const prevChar = str[i - 1]; if (char !== '_') { if (prevChar === '_') { out += char.toUpperCase(); } else { out += char; } } } return out; }
javascript
{ "resource": "" }
q20691
mapLastPart
train
function mapLastPart(mapper, separator) { return str => { const idx = str.lastIndexOf(separator); const mapped = mapper(str.slice(idx + separator.length)); return str.slice(0, idx + separator.length) + mapped; }; }
javascript
{ "resource": "" }
q20692
keyMapper
train
function keyMapper(mapper) { return obj => { if (!isObject(obj) || Array.isArray(obj)) { return obj; } const keys = Object.keys(obj); const out = {}; for (let i = 0, l = keys.length; i < l; ++i) { const key = keys[i]; out[mapper(key)] = obj[key]; } return out; }; }
javascript
{ "resource": "" }
q20693
normalizeIds
train
function normalizeIds(ids, prop, opt) { opt = opt || {}; let isComposite = prop.size > 1; let ret; if (isComposite) { // For composite ids these are okay: // // 1. [1, 'foo', 4] // 2. {a: 1, b: 'foo', c: 4} // 3. [[1, 'foo', 4], [4, 'bar', 1]] // 4. [{a: 1, b: 'foo', c: 4}, {a: 4, b: 'bar', c: 1}] // if (Array.isArray(ids)) { if (Array.isArray(ids[0])) { ret = new Array(ids.length); // 3. for (let i = 0, l = ids.length; i < l; ++i) { ret[i] = convertIdArrayToObject(ids[i], prop); } } else if (isObject(ids[0])) { ret = new Array(ids.length); // 4. for (let i = 0, l = ids.length; i < l; ++i) { ret[i] = ensureObject(ids[i], prop); } } else { // 1. ret = [convertIdArrayToObject(ids, prop)]; } } else if (isObject(ids)) { // 2. ret = [ids]; } else { throw new Error(`invalid composite key ${JSON.stringify(ids)}`); } } else { // For non-composite ids, these are okay: // // 1. 1 // 2. {id: 1} // 3. [1, 'foo', 4] // 4. [{id: 1}, {id: 'foo'}, {id: 4}] // if (Array.isArray(ids)) { if (isObject(ids[0])) { ret = new Array(ids.length); // 4. for (let i = 0, l = ids.length; i < l; ++i) { ret[i] = ensureObject(ids[i]); } } else { ret = new Array(ids.length); // 3. for (let i = 0, l = ids.length; i < l; ++i) { ret[i] = {}; prop.setProp(ret[i], 0, ids[i]); } } } else if (isObject(ids)) { // 2. ret = [ids]; } else { // 1. const obj = {}; prop.setProp(obj, 0, ids); ret = [obj]; } } checkProperties(ret, prop); if (opt.arrayOutput) { return normalizedToArray(ret, prop); } else { return ret; } }
javascript
{ "resource": "" }
q20694
forEachChildExpression
train
function forEachChildExpression(expr, modelClass, callback) { if (expr.node.$allRecursive || expr.maxRecursionDepth > RELATION_RECURSION_LIMIT) { throw modelClass.createValidationError({ type: ValidationErrorType.RelationExpression, message: `recursion depth of eager expression ${expr.toString()} too big for JoinEagerAlgorithm` }); } expr.forEachChildExpression(modelClass, callback); }
javascript
{ "resource": "" }
q20695
after
train
function after(obj, func) { if (isPromise(obj)) { return obj.then(func); } else { return func(obj); } }
javascript
{ "resource": "" }
q20696
promiseTry
train
function promiseTry(callback) { try { const maybePromise = callback(); if (isPromise(maybePromise)) { return maybePromise; } else { return Promise.resolve(maybePromise); } } catch (err) { return Promise.reject(err); } }
javascript
{ "resource": "" }
q20697
splitQueryProps
train
function splitQueryProps(model, json) { const keys = Object.keys(json); if (hasQueryProps(json, keys)) { const queryProps = {}; const modelProps = {}; for (let i = 0, l = keys.length; i < l; ++i) { const key = keys[i]; const value = json[key]; if (isQueryProp(value)) { queryProps[key] = value; } else { modelProps[key] = value; } } defineNonEnumerableProperty(model, QUERY_PROPS_PROPERTY, queryProps); return modelProps; } else { return json; } }
javascript
{ "resource": "" }
q20698
mergeQueryProps
train
function mergeQueryProps(model, json, omitProps, builder) { json = convertExistingQueryProps(json, builder); json = convertAndMergeHiddenQueryProps(model, json, omitProps, builder); return json; }
javascript
{ "resource": "" }
q20699
convertExistingQueryProps
train
function convertExistingQueryProps(json, builder) { const keys = Object.keys(json); for (let i = 0, l = keys.length; i < l; ++i) { const key = keys[i]; const value = json[key]; if (isQueryProp(value)) { json[key] = queryPropToKnexRaw(value, builder); } } return json; }
javascript
{ "resource": "" }