_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 27
233k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q0 | train | function (state, action) {
return _.defaults({
| javascript | {
"resource": ""
} |
|
q1 | addWidgetForFilter | train | function addWidgetForFilter (view, filter, editModeHint) {
var gridster = view._widgetsGridster;
var row = filter.row || 1;
var col = filter.col || 1;
var sizeX = filter.size_x || 3;
var sizeY = filter.size_y || 3;
var el = gridster.add_widget('<div class="widgetOuterFrame"></div>', sizeX, sizeY, col, row);
var frameView = new WidgetFrameView({
model: filter
});
// render, and render content of widget frame
view.renderSubview(frameView, el[0]);
frameView.renderContent();
// link element and view so we can:
// a) on remove, get to the HTMLElement from the | javascript | {
"resource": ""
} |
q2 | inRange | train | function inRange (value, min, max) {
const int = parseInt(value, 10)
return (
| javascript | {
"resource": ""
} |
q3 | markdown | train | function markdown(options) {
return new Remarkable(extend({
breaks: false,
html: true,
langPrefix: 'lang-',
linkify: true, | javascript | {
"resource": ""
} |
q4 | partitionValueToIndex | train | function partitionValueToIndex (partition, value) {
var group;
if (!partition) {
// no(sub)partitioning return first element
return 0;
}
// with (sub)partitioning
group = partition.groups.get(value, 'value');
| javascript | {
"resource": ""
} |
q5 | _validateArray | train | function _validateArray (path, model, validateModelType) {
const results = []
let subPath = `${path}/items`
if (_.isPlainObject(model.items)) {
if (model.items.type === 'object') {
results.push(validateSubModel(subPath, model.items, validateModelType))
}
} else if (Array.isArray(model.items)) {
| javascript | {
"resource": ""
} |
q6 | getDefaults | train | function getDefaults (value, path, model, resolveRef) {
const schema = findSchema(model, path, resolveRef)
const schemaDefault = _.clone(schema.default)
if (model.type === 'object') {
const subSchemaDefaults = {}
_.forIn(schema.properties, function (subSchema, propName) {
const defaults = getDefaults(
value && value[propName],
null,
subSchema,
resolveRef
)
if (defaults !== undefined) {
subSchemaDefaults[propName] = defaults
| javascript | {
"resource": ""
} |
q7 | getDefaultedValue | train | function getDefaultedValue ({inputValue, previousValue, bunsenId, renderModel, mergeDefaults}) {
const isInputValueEmpty = isEmptyValue(inputValue)
if (previousValue !== undefined) {
return inputValue
}
const resolveRef = schemaFromRef(renderModel.definitions)
const defaultValue = getDefaults(inputValue, bunsenId, renderModel, resolveRef)
const hasDefaults = defaultValue !== undefined
const isUpdatingAll = bunsenId === null
const shouldApplyDefaults = isInputValueEmpty && hasDefaults ||
!isInputValueEmpty && hasDefaults && isUpdatingAll && mergeDefaults
const | javascript | {
"resource": ""
} |
q8 | fieldValidation | train | function fieldValidation (dispatch, getState, fieldValidators, formValue, initialFormValue, all) {
let fieldsBeingValidated = []
const allValidationPromises = []
fieldValidators.forEach(validator => {
/**
* Field validator definition
* @property {String} field field to validate
* @property {String[]} fields fields to validate
* @property {Function} validator validation function to validate field/fields. Must return field within error/warning
* @property {Function[]} validators validation functions to validate field/fields. Must return field within error/warning
*/
const {field, fields, validator: validatorFunc, validators: validatorFuncs} = validator
const fieldsToValidate = fields || [field]
fieldsBeingValidated = fieldsBeingValidated.concat(fieldsToValidate)
fieldsToValidate.forEach((field) => {
let fieldValidationPromises = []
const newValue = _.get(formValue, field)
const oldValue = _.get(initialFormValue, field)
// Check if field value has changed
if (!_.isEqual(newValue, oldValue) || !initialFormValue) {
dispatchFieldIsValidating(dispatch, field, true)
const validations = validatorFuncs || [validatorFunc]
// Send validator formValue, the field we're validating against, and the field's value
validations.forEach((validatorFunc, index) => {
const fieldValidationPromise = validatorFunc(formValue, field, newValue)
.then((result) => {
const {
fieldValidationResult: {
errors: currentErrors = [],
warnings: currentWarnings = []
} = {}
} = getState()
const validationId = `${field}-${index}`
const filterOutValidationId = (item) => item.validationId !== validationId
const filteredOutErrors = currentErrors.filter(filterOutValidationId)
const filteredOutWarnings = currentWarnings.filter(filterOutValidationId)
// No need to use `aggregateResults as we should never have isRequired
const {
| javascript | {
"resource": ""
} |
q9 | _guardPromiseAll | train | function _guardPromiseAll (promises, all, callback) {
if (promises.length === | javascript | {
"resource": ""
} |
q10 | getPropertyOrder | train | function getPropertyOrder (properties) {
const primitiveProps = []
const complexProps = []
_.forIn(properties, (prop, propName) => {
if (prop.type === 'object' || prop.type === 'array') {
| javascript | {
"resource": ""
} |
q11 | addModelCell | train | function addModelCell (propertyName, model, cellDefinitions) {
const cell = {}
var defName = propertyName
var counter = 1
while (defName in cellDefinitions) {
defName = `${propertyName}${counter}`
counter++
}
cellDefinitions[defName] = cell
const props = getPropertyOrder(model.properties)
const children = props.map((propName) => {
// we have a circular dependency
/* eslint-disable no-use-before-define */
return | javascript | {
"resource": ""
} |
q12 | run | train | async function run() {
// Read the records
const records = await BB.all(process.argv.slice(2).map(f => readAsync(f)))
// Write them to Kinesis
return BB.map(records, record => kinesis.putRecord({
| javascript | {
"resource": ""
} |
q13 | appendModelPath | train | function appendModelPath (modelPath, id, internal) {
const addedModelPath = getModelPath(id)
if (internal) {
if (modelPath === '') {
return `properties._internal.${addedModelPath}`
}
| javascript | {
"resource": ""
} |
q14 | extendCell | train | function extendCell (cell, cellDefinitions) {
cell = _.clone(cell)
while (cell.extends) {
const extendedCell = cellDefinitions[cell.extends]
if (!_.isObject(extendedCell)) {
throw new Error(`'${cell.extends}' is not | javascript | {
"resource": ""
} |
q15 | normalizeArrayOptions | train | function normalizeArrayOptions (cell, cellDefinitions) {
const arrayOptions = _.clone(cell.arrayOptions)
if (arrayOptions.itemCell) {
if (Array.isArray(arrayOptions.itemCell)) {
arrayOptions.itemCell = arrayOptions.itemCell.map(cell => normalizeCell(cell, cellDefinitions))
} else {
arrayOptions.itemCell = | javascript | {
"resource": ""
} |
q16 | pluckFromArrayOptions | train | function pluckFromArrayOptions (cell, modelPath, models, cellDefinitions) {
if (cell.arrayOptions.tupleCells) {
cell.arrayOptions.tupleCells.forEach(function (cell, index) {
pluckModels(cell, modelPath.concat(index), models, cellDefinitions)
})
}
if (cell.arrayOptions.itemCell) {
const itemCell = cell.arrayOptions.itemCell
if (Array.isArray(itemCell)) {
itemCell.forEach(function (cell, | javascript | {
"resource": ""
} |
q17 | pluckModels | train | function pluckModels (cell, modelPath, models, cellDefinitions) {
cell = extendCell(cell, cellDefinitions)
if (_.isObject(cell.model)) {
const addedPath = appendModelPath(modelPath.modelPath(), cell.id, cell.internal)
models[addedPath] = cell.model
} else if (cell.children) { // recurse on objects
cell.children.forEach((cell) => {
const newPath = typeof cell.model === 'string' ? modelPath.concat(cell.model) : modelPath
| javascript | {
"resource": ""
} |
q18 | aggregateModels | train | function aggregateModels (view, modelPath) {
const models = {}
view.cells.forEach(function (cell) {
const newPath = typeof cell.model === 'string' ? modelPath.concat(cell.model) : | javascript | {
"resource": ""
} |
q19 | expandModel | train | function expandModel (model, view) {
const modelPath = new BunsenModelPath(model)
const modelExpansions = aggregateModels(view, modelPath)
let newModel = model
| javascript | {
"resource": ""
} |
q20 | svgs | train | function svgs(req, res) {
const bundle = new Bundle(
req.url.slice(1, -5).split('-').map(function map(name) {
return assets[name];
})
);
bundle.run(function (err, output) {
if (err) throw | javascript | {
"resource": ""
} |
q21 | html | train | function html(req, res) {
fs.readFile(path.join(__dirname, 'index.html'), function read(err, file) {
| javascript | {
"resource": ""
} |
q22 | client | train | function client(req, res) {
const compiler = webpack(config);
compiler.outputFileSystem = fsys;
compiler.run((err, stats) => {
const file = fsys.readFileSync(path.join(__dirname, 'dist', 'client.js'));
| javascript | {
"resource": ""
} |
q23 | convertObjectCell | train | function convertObjectCell (cell) {
return _.chain(cell.rows)
.map(rowsToCells)
| javascript | {
"resource": ""
} |
q24 | convertArrayCell | train | function convertArrayCell (cell) {
const {item} = cell
const arrayOptions = _.chain(item)
.pick(ARRAY_CELL_PROPERTIES)
.assign({
itemCell: convertCell(item) | javascript | {
"resource": ""
} |
q25 | convertRenderer | train | function convertRenderer (cell) {
const {renderer} = cell
if (renderer === undefined) {
return
}
const basicRenderers = [
'boolean',
'string',
'number'
| javascript | {
"resource": ""
} |
q26 | grabClassNames | train | function grabClassNames (cell) {
const classNames = _.pickBy({
cell: cell.className,
value: cell.inputClassName,
| javascript | {
"resource": ""
} |
q27 | rowsToCells | train | function rowsToCells (rows) {
if (!rows) {
return {}
}
const children = rows
.map((row) => {
return {
| javascript | {
"resource": ""
} |
q28 | warning | train | function warning(lines) {
lines.unshift(''); // Extra whitespace at the start.
lines.push(''); | javascript | {
"resource": ""
} |
q29 | viewBox | train | function viewBox(details) {
svg.viewBox = `${details.x || 0} ${details.y || | javascript | {
"resource": ""
} |
q30 | train | function () {
var filter = this.collection.parent.filter;
if (!filter || !this.isFilled) {
return false;
}
filter.releaseDataFilter();
if (this.type === 'partition') {
var partition = filter.partitions.get(this.rank, 'rank');
filter.partitions.remove(partition);
} else if | javascript | {
"resource": ""
} |
|
q31 | getWebpackRunnableLambda | train | function getWebpackRunnableLambda(slsWebpack, stats, functionName) {
const handler = slsWebpack.loadHandler(stats, | javascript | {
"resource": ""
} |
q32 | onClick | train | function onClick (ev, elements) {
var model = this._Ampersandview.model;
var partition = model.filter.partitions.get(1, 'rank');
if (elements.length > 0) {
| javascript | {
"resource": ""
} |
q33 | getColor | train | function getColor (i) {
i = parseInt(i);
if (i < 0 || i >= colors.length) {
// pick a color from | javascript | {
"resource": ""
} |
q34 | init | train | function init(loader) {
var loaderConfig = loaderUtils.getLoaderConfig(loader, 'web3Loader');
web3 = | javascript | {
"resource": ""
} |
q35 | mergeConfig | train | function mergeConfig(loaderConfig) {
var defaultConfig = {
// Web3
provider: 'http://localhost:8545',
// For deployment
from: web3.eth.accounts[0],
gasLimit: web3.eth.getBlock(web3.eth.defaultBlock).gasLimit,
// Specify contract constructor parameters, if any.
// constructorParams: {
// ContractOne: [ 'param1_value', 'param2_value' ]
// }
constructorParams: {},
// To use deployed contracts instead of redeploying, include contract addresses in config
| javascript | {
"resource": ""
} |
q36 | deploy | train | function deploy(contract, callback, contractMap) {
// Reuse existing contract address
if (config.deployedContracts.hasOwnProperty(contract.name)) {
contract.address = config.deployedContracts[contract.name];
return callback(null, contract);
}
linkBytecode(contract, contractMap);
// Deploy a new one
var params = resolveConstructorParams(contract, contractMap);
logDebug('Constructor params ' + contract.name + ':', params);
if(contract.bytecode && !contract.bytecode.startsWith('0x')) {
contract.bytecode = '0x' + contract.bytecode;
}
params.push({
from: config.from,
| javascript | {
"resource": ""
} |
q37 | _validateRootAttributes | train | function _validateRootAttributes (view, model, cellValidator) {
const results = [
_validateCells(view, model, cellValidator)
]
const knownAttributes = ['version', 'type', 'cells', 'cellDefinitions']
const unknownAttributes = _.difference(Object.keys(view), knownAttributes)
results.push({
errors: [],
| javascript | {
"resource": ""
} |
q38 | train | function () {
// Create and attach our main view
this.mainView = new MainView({
model: this.me,
el: document.body
});
// this kicks off our backbutton tracking (browser history)
// and will cause the first | javascript | {
"resource": ""
} |
|
q39 | train | function (i) {
if (i >= columns.length) {
insertIntoDB();
return;
}
var dbField = columns[i];
var field = dbField.Field;
//Check required fields
if (dbField.Null === 'NO' &&
dbField.Default === '' &&
dbField.Extra !== 'auto_increment' &&
dbField.Extra.search('on update')===-1) {
//Check if field not set
if (undefOrEmpty(req.body[field])) {
return sendError(res,"Field " + field + " is NOT NULL but not specified in this request");
} else {
//Check if the set values are roughly okay
value = checkIfSentvaluesAreSufficient(req,dbField);
console.log(value);
if(value !== false) {
//Value seems okay, go to the next field
insertJson[field] = value;
iterator(i + 1);
} else {
return sendError(res,'Value for field ' + field + ' is not sufficient. Expecting ' + dbField.Type + ' but got ' + typeof req.body[field] );
}
}
} else {
//Check for not required fields
//Skip auto_incremented fields
if(dbField.Extra === 'auto_increment') {
iterator(i + 1);
} else {
//Check if the field was provided by the client
var defined = false;
if(dbField.Default == "FILE") {
if(req.files.hasOwnProperty(dbField.Field)) {
defined = true;
}
} else {
if(typeof req.body[field] !== "undefined") {
defined = true;
}
| javascript | {
"resource": ""
} |
|
q40 | insertIntoDB | train | function insertIntoDB() {
lastQry = connection.query('INSERT INTO ?? SET ?', [req.params.table , insertJson] , function (err, rows) {
if (err) {
console.error(err);
| javascript | {
"resource": ""
} |
q41 | updateIntoDB | train | function updateIntoDB() {
//Yaaay, alle Tests bestanden gogo, insert!
lastQry = connection.query('UPDATE ?? SET ? WHERE ?? = ?', [req.params.table , updateJson, updateSelector.field, updateSelector.value] , function (err) {
if (err) return sendError(res,err.code);
| javascript | {
"resource": ""
} |
q42 | sendSuccessAnswer | train | function sendSuccessAnswer(table, res, id, field) {
if(typeof field === "undefined") {
if(id === 0) {
//Just assume that everything went okay. It looks like a non numeric primary key.
res.send({
result: 'success',
table: table
});
return;
} else {
field = "id";
}
}
lastQry = | javascript | {
"resource": ""
} |
q43 | checkIfSentvaluesAreSufficient | train | function checkIfSentvaluesAreSufficient(req,dbField) {
if(dbField.Default == 'FILE') {
//For 'File' fields just return the link ot the file
if(req.files.hasOwnProperty(dbField.Field)) {
var file = req.files[dbField.Field].hasOwnProperty('name') ? req.files[dbField.Field] : req.files[dbField.Field][0];
if(settings.maxFileSize !== -1 && file.size > settings.maxFileSize) {
return false;
| javascript | {
"resource": ""
} |
q44 | sendError | train | function sendError(res,err) {
console.error(err);
// also log last executed query, for easier debugging
console.error(lastQry.sql);
| javascript | {
"resource": ""
} |
q45 | findPrim | train | function findPrim(columns,field) {
var primary_keys = columns.filter(function (r) {return r.Key === 'PRI';});
//for multiple primary keys, just take the first
if(primary_keys.length > 0) {
return primary_keys[0].Field;
}
//If the provided field is a string, we might have a chance
| javascript | {
"resource": ""
} |
q46 | checkRateRange | train | function checkRateRange(num) {
var numString = num.substring(0, num.length - 1);
var parseNum = parseInt(numString);
if (parseNum < 20) {
| javascript | {
"resource": ""
} |
q47 | isInList | train | function isInList(value, listOfValues, msg) {
value = value.toLowerCase().trim();
| javascript | {
"resource": ""
} |
q48 | equals | train | function equals(x, y) {
var a = isFunction(x) ? x() : x;
var b = isFunction(y) ? y() : y;
var aKeys;
if (a == b)
return true;
else if (a == _null || b == _null)
return false;
else if (isValue(a) || isValue(b))
return isDate(a) && isDate(b) && +a==+b;
else if (isList(a)) {
return (a.length == b.length) &&
!find(a, function(val, index) {
if (!equals(val, b[index]))
return true;
| javascript | {
"resource": ""
} |
q49 | parseDate | train | function parseDate(fmt, date) {
var indexMap = {}; // contains reGroupPosition -> typeLetter or [typeLetter, value array]
var reIndex = 1;
var timezoneOffsetMatch;
var timezoneIndex;
var match;
var format = replace(fmt, /^\?/);
if (format!=fmt && !trim(date))
return _null;
if (match = /^\[([+-])(\d\d)(\d\d)\]\s*(.*)/.exec(format)) {
timezoneOffsetMatch = match;
format = match[4];
}
var parser = new RegExp(format.replace(/(.)(\1*)(?:\[([^\]]*)\])?/g, function(wholeMatch, placeholderChar, placeholderDigits, param) {
if (/[dmhkyhs]/i.test(placeholderChar)) {
indexMap[reIndex++] = placeholderChar;
var plen = placeholderDigits.length+1;
return "(\\d"+(plen<2?"+":("{1,"+plen+"}"))+")";
}
else if (placeholderChar == 'z') {
timezoneIndex = reIndex;
reIndex += 3;
return "([+-])(\\d\\d)(\\d\\d)";
}
else if (/[Nna]/.test(placeholderChar)) {
indexMap[reIndex++] = [placeholderChar, param && param.split(',')];
return "([a-zA-Z\\u0080-\\u1fff]+)";
}
else if (/w/i.test(placeholderChar))
return "[a-zA-Z\\u0080-\\u1fff]+";
else if (/\s/.test(placeholderChar))
return "\\s+";
else
return escapeRegExp(wholeMatch);
}));
if (!(match = parser.exec(date)))
return undef;
var ctorArgs = [0, 0, 0, 0, 0, 0, 0];
for (var i = 1; i < reIndex; i++) {
var matchVal = match[i];
var indexEntry = indexMap[i];
| javascript | {
"resource": ""
} |
q50 | collectUniqNodes | train | function collectUniqNodes(list, func) {
var result = [];
var nodeIds = {};
var currentNodeId;
flexiEach(list, function(value) {
flexiEach(func(value), function(node) {
if (!nodeIds[currentNodeId = getNodeId(node)]) | javascript | {
"resource": ""
} |
q51 | triggerHandler | train | function triggerHandler(eventName, event, target) {
var match = !bubbleSelector;
var el = bubbleSelector ? target : registeredOn;
if (bubbleSelector) {
var selectorFilter = getFilterFunc(bubbleSelector, registeredOn);
while (el && el != registeredOn && !(match = selectorFilter(el)))
| javascript | {
"resource": ""
} |
q52 | enrichMethodNode | train | function enrichMethodNode(methodNode, method) {
method.description && (methodNode.description = method.description)
if (method.tags.route) {
let httpPath = method.tags.route
let httpMethod = 'GET'
const sepPos = httpPath.indexOf(' ')
if (sepPos !== -1) {
httpMethod = httpPath.substr(0, sepPos).toUpperCase()
httpPath = httpPath.substr(sepPos + 1)
| javascript | {
"resource": ""
} |
q53 | refract | train | function refract(value) {
if (value instanceof Element) {
return value;
}
if (typeof value === 'string') {
return new StringElement(value);
}
if (typeof value === 'number') {
return new NumberElement(value);
}
if (typeof value === 'boolean') {
return new BooleanElement(value);
}
if (value === null) {
return new NullElement(); | javascript | {
"resource": ""
} |
q54 | statusLog | train | function statusLog(file, data, time) {
var msg = '';
var diff = (process.hrtime(time)[1] / 1000000000).toFixed(2);
var adapters = Object.keys(data._adapterData).join(', ');
msg += format('Supercollider: processed %s | javascript | {
"resource": ""
} |
q55 | CodeMirror | train | function CodeMirror(place, options) {
if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
this.options = options = options ? copyObj(options) : {};
// Determine effective options based on given values and defaults.
copyObj(defaults, options, false);
setGuttersForLineNumbers(options);
var doc = options.value;
if (typeof doc == "string") doc = new Doc(doc, options.mode);
this.doc = doc;
var display = this.display = new Display(place, doc);
display.wrapper.CodeMirror = this;
updateGutters(this);
themeChanged(this);
if (options.lineWrapping)
this.display.wrapper.className += " CodeMirror-wrap";
if (options.autofocus && !mobile) focusInput(this);
initScrollbars(this);
this.state = {
keyMaps: [], // stores maps added by addKeyMap
overlays: [], // highlighting overlays, as added by addOverlay
modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
overwrite: false, focused: false,
suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in readInput
draggingText: false,
highlight: new Delayed(), // stores highlight worker timeout
keySeq: null // Unfinished key sequence
};
// Override magic textarea content restore that IE sometimes does
// on our hidden textarea on reload
if (ie && ie_version < 11) setTimeout(bind(resetInput, this, true), 20);
registerEventHandlers(this);
ensureGlobalHandlers();
startOperation(this);
| javascript | {
"resource": ""
} |
q56 | updateWidgetHeight | train | function updateWidgetHeight(line) {
if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
| javascript | {
"resource": ""
} |
q57 | ensureLineWrapped | train | function ensureLineWrapped(lineView) {
if (lineView.node == lineView.text) {
lineView.node = elt("div", null, null, "position: relative");
if (lineView.text.parentNode)
| javascript | {
"resource": ""
} |
q58 | extendSelection | train | function extendSelection(doc, head, other, options) {
setSelection(doc, new Selection([extendRange(doc, | javascript | {
"resource": ""
} |
q59 | skipAtomic | train | function skipAtomic(doc, pos, bias, mayClear) {
var flipped = false, curPos = pos;
var dir = bias || 1;
doc.cantEdit = false;
search: for (;;) {
var line = getLine(doc, curPos.line);
if (line.markedSpans) {
for (var i = 0; i < line.markedSpans.length; ++i) {
var sp = line.markedSpans[i], m = sp.marker;
if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
(sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
if (mayClear) {
signal(m, "beforeCursorEnter");
if (m.explicitlyCleared) {
if (!line.markedSpans) break;
else {--i; continue;}
}
}
if (!m.atomic) continue;
var newPos = | javascript | {
"resource": ""
} |
q60 | drawSelectionCursor | train | function drawSelectionCursor(cm, range, output) {
var pos = cursorCoords(cm, range.head, "div", null, null, !cm.options.singleCursorHeightPerLine);
var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
cursor.style.left = pos.left + "px";
cursor.style.top = pos.top + "px";
cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
if (pos.other) {
// Secondary cursor, shown when on a 'jump' in bi-directional text
| javascript | {
"resource": ""
} |
q61 | findViewForLine | train | function findViewForLine(cm, lineN) {
if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
return cm.display.view[findViewIndex(cm, lineN)];
var ext = | javascript | {
"resource": ""
} |
q62 | prepareMeasureForLine | train | function prepareMeasureForLine(cm, line) {
var lineN = lineNo(line);
var view = findViewForLine(cm, lineN);
if (view && !view.text)
view = null;
else if (view && view.changes)
updateLineForChanges(cm, view, lineN, getDimensions(cm));
if (!view)
view = updateExternalMeasurement(cm, | javascript | {
"resource": ""
} |
q63 | charWidth | train | function charWidth(display) {
if (display.cachedCharWidth != null) return display.cachedCharWidth;
var anchor = elt("span", "xxxxxxxxxx");
var pre = | javascript | {
"resource": ""
} |
q64 | endOperation | train | function endOperation(cm) {
var op = cm.curOp, group = op.ownsGroup;
if (!group) return;
try { fireCallbacksForOps(group); }
finally {
operationGroup = null;
| javascript | {
"resource": ""
} |
q65 | setScrollTop | train | function setScrollTop(cm, val) {
if (Math.abs(cm.doc.scrollTop - val) < 2) return;
cm.doc.scrollTop = val;
if (!gecko) updateDisplaySimple(cm, {top: | javascript | {
"resource": ""
} |
q66 | ensureCursorVisible | train | function ensureCursorVisible(cm) {
resolveScrollToPos(cm);
var cur = cm.getCursor(), from = cur, to = cur;
if (!cm.options.lineWrapping) {
| javascript | {
"resource": ""
} |
q67 | takeToken | train | function takeToken(cm, pos, precise, asArray) {
function getObj(copy) {
return {start: stream.start, end: stream.pos,
string: stream.current(),
type: style || null,
state: copy ? copyState(doc.mode, state) : state};
}
var doc = cm.doc, mode = doc.mode, style;
pos = clipPos(doc, pos);
var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
var stream = new StringStream(line.text, cm.options.tabSize), tokens;
| javascript | {
"resource": ""
} |
q68 | buildLineContent | train | function buildLineContent(cm, lineView) {
// The padding-right forces the element to have a 'border', which
// is needed on Webkit to be able to get line-level bounding
// rectangles for it (in measureChar).
var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
var builder = {pre: elt("pre", [content]), content: content, col: 0, pos: 0, cm: cm};
lineView.measure = {};
// Iterate over the logical lines that make up this visual line.
for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
var line = i ? lineView.rest[i - 1] : lineView.line, order;
builder.pos = 0;
builder.addToken = buildToken;
// Optionally wire in some hacks into the token-rendering
// algorithm, to deal with browser quirks.
if ((ie || webkit) && cm.getOption("lineWrapping"))
builder.addToken = buildTokenSplitSpaces(builder.addToken);
if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
builder.addToken = buildTokenBadBidi(builder.addToken, order);
builder.map = [];
var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
if (line.styleClasses) {
if (line.styleClasses.bgClass)
builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
if (line.styleClasses.textClass)
builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
}
// Ensure at least a single node is present, for measuring.
if (builder.map.length == 0)
| javascript | {
"resource": ""
} |
q69 | buildToken | train | function buildToken(builder, text, style, startStyle, endStyle, title, css) {
if (!text) return;
var special = builder.cm.options.specialChars, mustWrap = false;
if (!special.test(text)) {
builder.col += text.length;
var content = document.createTextNode(text);
builder.map.push(builder.pos, builder.pos + text.length, content);
if (ie && ie_version < 9) mustWrap = true;
builder.pos += text.length;
} else {
var content = document.createDocumentFragment(), pos = 0;
while (true) {
special.lastIndex = pos;
var m = special.exec(text);
var skipped = m ? m.index - pos : text.length - pos;
if (skipped) {
var txt = document.createTextNode(text.slice(pos, pos + skipped));
if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
else content.appendChild(txt);
builder.map.push(builder.pos, builder.pos + skipped, txt);
builder.col += skipped;
builder.pos += skipped;
}
if (!m) break;
pos += skipped + 1;
if (m[0] == "\t") {
var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
| javascript | {
"resource": ""
} |
q70 | train | function(at, lines, height) {
this.height += height;
this.lines = this.lines.slice(0, | javascript | {
"resource": ""
} |
|
q71 | clearSelectionEvents | train | function clearSelectionEvents(array) {
while (array.length) {
var last = lst(array);
if | javascript | {
"resource": ""
} |
q72 | train | function() {
// don't create more object URLs than needed
if (blob_changed || !object_url) {
object_url = get_URL().createObjectURL(blob);
}
if (target_view) {
target_view.location.href = object_url;
} else {
var new_tab = view.open(object_url, "_blank");
if (new_tab == undefined && typeof safari !== "undefined") {
| javascript | {
"resource": ""
} |
|
q73 | DOMMouseMoveTracker | train | function DOMMouseMoveTracker(
onMove,
/*function*/ onMoveEnd,
/*DOMElement*/ domNode) {
this.$DOMMouseMoveTracker_isDragging = false;
this.$DOMMouseMoveTracker_animationFrameID = null;
this.$DOMMouseMoveTracker_domNode = domNode;
this.$DOMMouseMoveTracker_onMove | javascript | {
"resource": ""
} |
q74 | train | function(target, eventType, callback) {
if (target.addEventListener) {
target.addEventListener(eventType, callback, false);
return {
remove: function() {
target.removeEventListener(eventType, callback, false); | javascript | {
"resource": ""
} |
|
q75 | train | function(
/*number*/ combinedWidth,
/*number*/ leftOffset,
/*number*/ cellWidth,
/*?number*/ cellMinWidth,
/*?number*/ cellMaxWidth,
/*number|string*/ columnKey,
/*object*/ event) {
if (Locale.isRTL()) {
leftOffset = -leftOffset;
}
| javascript | {
"resource": ""
} |
|
q76 | forEachColumn | train | function forEachColumn(children, callback) {
React.Children.forEach(children, function(child) {
if (child.type === FixedDataTableColumnGroup.type) {
forEachColumn(child.props.children, | javascript | {
"resource": ""
} |
q77 | mapColumns | train | function mapColumns(children, callback) {
var newChildren = [];
React.Children.forEach(children, function(originalChild) {
var newChild = originalChild;
// The child is either a column group or a column. If it is a column group
// we need to iterate over its columns and then potentially generate a
// new column group
if (originalChild.type === FixedDataTableColumnGroup.type) {
var haveColumnsChanged = false;
var newColumns = [];
forEachColumn(originalChild.props.children, function(originalcolumn) {
var newColumn = callback(originalcolumn);
if (newColumn !== originalcolumn) {
haveColumnsChanged = true;
}
newColumns.push(newColumn);
| javascript | {
"resource": ""
} |
q78 | FixedDataTableRowBuffer | train | function FixedDataTableRowBuffer(
rowsCount,
/*number*/ defaultRowHeight,
/*number*/ viewportHeight,
/*?function*/ rowHeightGetter)
{
invariant(
defaultRowHeight !== 0,
"defaultRowHeight musn't be equal 0 in FixedDataTableRowBuffer"
);
this.$FixedDataTableRowBuffer_bufferSet = new IntegerBufferSet();
this.$FixedDataTableRowBuffer_defaultRowHeight = defaultRowHeight;
this.$FixedDataTableRowBuffer_viewportRowsBegin = 0;
this.$FixedDataTableRowBuffer_viewportRowsEnd = 0;
this.$FixedDataTableRowBuffer_maxVisibleRowCount = Math.ceil(viewportHeight / defaultRowHeight) + 1;
this.$FixedDataTableRowBuffer_bufferRowsCount = clamp(
MIN_BUFFER_ROWS,
| javascript | {
"resource": ""
} |
q79 | cx | train | function cx(classNames) {
var classNamesArray;
if (typeof classNames == 'object') {
classNamesArray = Object.keys(classNames).filter(function(className) {
return classNames[className];
});
} else | javascript | {
"resource": ""
} |
q80 | train | function(obj) {
var ret = {};
var key;
invariant(
obj instanceof Object && !Array.isArray(obj),
'keyMirror(...): Argument must be an object.'
);
for (key in obj) {
| javascript | {
"resource": ""
} |
|
q81 | shallowEqual | train | function shallowEqual(objA, objB) {
if (objA === objB) {
return true;
}
var key;
// Test for A's keys different from B.
for (key in objA) {
if (objA.hasOwnProperty(key) &&
(!objB.hasOwnProperty(key) || objA[key] !== objB[key])) {
return false;
}
}
// Test for | javascript | {
"resource": ""
} |
q82 | train | function(a){var b;
// the final two arguments are the length, and the entire string itself;
// we don't care about those. | javascript | {
"resource": ""
} |
|
q83 | FakeEvent | train | function FakeEvent(type, bubbles, cancelable, target) {
| javascript | {
"resource": ""
} |
q84 | padcomments | train | function padcomments(str, num) {
var nl = _str.repeat('\n', | javascript | {
"resource": ""
} |
q85 | train | function(obj, cache) {
cache[obj.cid] = obj;
this.listenToOnce(obj, 'before-dispose', function() | javascript | {
"resource": ""
} |
|
q86 | hotswap | train | function hotswap(currentNode, newNode, ignoreElements) {
var newNodeType = newNode.nodeType,
currentNodeType = currentNode.nodeType,
swapMethod;
if(newNodeType !== currentNodeType) {
$(currentNode).replaceWith(newNode);
| javascript | {
"resource": ""
} |
q87 | cleanupStickitData | train | function cleanupStickitData(node) {
var $node = $(node);
var stickitValue = $node.data('stickit-bind-val');
if (node.tagName === 'OPTION' && | javascript | {
"resource": ""
} |
q88 | train | function($el, template, context, opts) {
var newDOM, newHTML,
el = $el.get(0);
opts = opts || {};
newHTML = opts.newHTML || template(context);
if (opts.force) {
$el.html(newHTML);
} else {
newDOM | javascript | {
"resource": ""
} |
|
q89 | train | function(currentNode, newNode, ignoreElements) {
var currentCaret, activeElement,
currentNodeContainsActiveElement = false;
try {
activeElement = document.activeElement;
} catch (error) {
activeElement = null;
}
if (activeElement && currentNode && $.contains(activeElement, currentNode)) {
currentNodeContainsActiveElement = true;
}
if (currentNodeContainsActiveElement && this.supportsSelection(activeElement)) {
| javascript | {
"resource": ""
} |
|
q90 | train | function(el) {
var newDOM = document.createElement(el.tagName);
_.each(el.attributes, function(attrib) {
| javascript | {
"resource": ""
} |
|
q91 | train | function(options) {
options = options || {};
options.idsToFetch = options.idsToFetch || this.trackedIds;
options.setOptions = options.setOptions || {remove: false};
return this.__loadWrapper(function() {
if (options.idsToFetch && options.idsToFetch.length) {
| javascript | {
"resource": ""
} |
|
q92 | train | function(ids, options) {
options = options || {};
options.idsToFetch = _.intersection(ids, | javascript | {
"resource": ""
} |
|
q93 | train | function(ids) {
this.remove(_.difference(this.trackedIds, ids));
| javascript | {
"resource": ""
} |
|
q94 | train | function(options) {
options = options || {};
//find ids that we don't have in cache and aren't already in the process of being fetched.
var idsNotInCache = _.difference(this.getTrackedIds(), _.pluck(parentInstance.models, 'id'));
var idsWithPromises = _.pick(parentInstance.idPromises, idsNotInCache);
// Determine which ids are already being fetched and the associated promises for those ids.
options.idsToFetch = _.difference(idsNotInCache, _.uniq(_.flatten(_.keys(idsWithPromises))));
var thisFetchPromise = this.fetch(options);
// Return a promise that resolves when all ids are fetched (including pending ids).
var allPromisesToWaitFor = _.flatten(_.values(idsWithPromises));
allPromisesToWaitFor.push(thisFetchPromise);
var allUniquePromisesToWaitFor = _.uniq(allPromisesToWaitFor);
return $.when.apply($, allUniquePromisesToWaitFor)
| javascript | {
"resource": ""
} |
|
q95 | train | function(modelIdentifier) {
var model = this.get(modelIdentifier);
parentClass.remove.apply(this, arguments);
if (model) {
| javascript | {
"resource": ""
} |
|
q96 | train | function(args) {
base.call(this, args);
this.loadedOnceDeferred = new $.Deferred();
this.loadedOnce = false;
this.loadingCount = 0;
| javascript | {
"resource": ""
} |
|
q97 | train | function(fetchMethod, options) {
var object = this;
this.loadingCount++;
this.loading = true;
this.trigger('load-begin');
return $.when(fetchMethod.call(object, options)).always(function() {
if (!object.loadedOnce) {
object.loadedOnce = true;
object.loadedOnceDeferred.resolve();
}
object.loadingCount--;
if (object.loadingCount <= 0) {
object.loadingCount = 0; // prevent going negative.
object.loading = false;
}
| javascript | {
"resource": ""
} |
|
q98 | train | function(viewPrepare) {
var viewContext = viewPrepare() || {};
var behaviorContext = _.omit(this.toJSON(), 'view');
_.extend(behaviorContext, this.prepare()); | javascript | {
"resource": ""
} |
|
q99 | train | function() {
this.listenTo(this.view, 'initialize:complete', this.__augmentViewPrepare);
this.listenTo(this.view, 'before-dispose-callback', this.__dispose);
_.each(eventMap, | javascript | {
"resource": ""
} |