_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q8800
|
proxy
|
train
|
function proxy(scope, map, emitter) {
var args = slice.call(arguments, 3)
, tmp = {}, len, name, methods, method, i
if (isArray(map)) {
len = map.length
while (len--) {
tmp[map[len]] = map[len]
}
map = tmp
}
for (name in map) {
methods = map[name]
if (!isArray(methods)) {
methods = [methods]
}
for (i = 0; i < methods.length; i++) {
method = methods[i]
if (typeof method === 'string') {
method = scope[method]
}
if (!method) {
throw new Error('Proxy: method `' + method + '` does not exist')
}
emitter[listener](name, bind.apply(scope, concat.apply([scope, method], args)))
}
}
}
|
javascript
|
{
"resource": ""
}
|
q8801
|
train
|
function() {
ElementController.call(this, this.observations);
this.observersEnabled = false;
this.listenersEnabled = false;
if (this.expression && this.updated !== Binding.prototype.updated) {
// An observer to observe value changes to the expression within a context
this.observer = this.watch(this.expression, this.updated);
}
this.created();
}
|
javascript
|
{
"resource": ""
}
|
|
q8802
|
initNodePath
|
train
|
function initNodePath(node, view) {
var path = [];
while (node !== view) {
var parent = node.parentNode;
path.unshift(indexOf.call(parent.childNodes, node));
node = parent;
}
return path;
}
|
javascript
|
{
"resource": ""
}
|
q8803
|
BrotliFilter
|
train
|
function BrotliFilter(inputNode, options) {
if (!(this instanceof BrotliFilter))
return new BrotliFilter(inputNode, options);
options = options || {};
this.brotliOptions = {
mode: options.mode || 0,
quality: options.quality || 11,
lgwin: options.lgwin || 22,
lgblock: options.lgblock || 0
};
this.keepUncompressed = options.keepUncompressed;
this.appendSuffix = (options.hasOwnProperty('appendSuffix') ?
options.appendSuffix :
true);
// Default file encoding is raw to handle binary files
this.inputEncoding = options.inputEncoding || null;
this.outputEncoding = options.outputEncoding || null;
if (this.keepUncompressed && !this.appendSuffix) {
throw new Error('Cannot keep uncompressed files without appending suffix. Filenames would be the same.');
}
Filter.call(this, inputNode, options);
}
|
javascript
|
{
"resource": ""
}
|
q8804
|
train
|
function (o, cb) {
try {
var reader = new FileReader();
reader.onload = function (event) {
cb && cb(reader.result);
};
reader.readAsText(o);
} catch (error) {
throw error
}
}
|
javascript
|
{
"resource": ""
}
|
|
q8805
|
train
|
function (param, allowTypes) {
var t$ = Tool;
allowTypes = allowTypes || [];
if (t$.isUndefinedOrNull(param)) { return [] }
if (allowTypes.findIndex(function (value, index, err) {
return value === t$.getType(param)
}) > -1) {
return [param]
}
if (t$.isArray(param)) { return param }
return []
}
|
javascript
|
{
"resource": ""
}
|
|
q8806
|
train
|
function (err) {
var msg = '';
var t$ = Tool;
try {
if (t$.isString(err)) {
msg = err;
} else if (t$.isError(err)) {
msg = err.message;
} else if (t$.isObject(err)) {
var errMsg = [];
for (var p in err) {
if (err.hasOwnProperty(p)) {
errMsg.push(p + '=' + err[p]);
}
}
if (errMsg.length === 0) {
msg = err;
} else {
msg = errMsg.join('\n');
}
} else {
msg += '[RTY_CANT_TYPE] = ' + t$.getType(err);
msg += JSON.stringify(err);
}
} catch (error) {
throw error
}
return msg
}
|
javascript
|
{
"resource": ""
}
|
|
q8807
|
train
|
function (fileName, fileTypes) {
var _fileNameStr = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length).toLowerCase();
if (fileTypes.indexOf(_fileNameStr) > -1) { return true }
return false
}
|
javascript
|
{
"resource": ""
}
|
|
q8808
|
outer
|
train
|
function outer(A, B) {
if (A.shape.length === 1) {
A.reshape([A.shape[0], 1]);
}
else if (A.shape.length === 2) {
if (A.shape[1] !== 1) {
throw new Error('A is not a column vector');
}
}
else {
throw new Error('A has invalid dimensions');
}
if (B.shape.length === 1) {
B.reshape([1, B.shape[0]]);
}
else if (B.shape.length === 2) {
if (B.shape[0] !== 1) {
throw new Error('B is not a row vector');
}
}
else {
throw new Error('B has invalid dimensions');
}
if (A.shape[0] !== B.shape[1]) {
throw new Error('Sizes of A and B are not compatible');
}
return matmul(A, B);
}
|
javascript
|
{
"resource": ""
}
|
q8809
|
cholesky
|
train
|
function cholesky(A) {
if (A.shape.length !== 2) {
throw new Error('A is not a matrix');
}
if (A.shape[0] !== A.shape[1]) {
throw new Error('Input is not square matrix');
}
var copyA = A.clone();
copyA.swapOrder();
lapack.potrf(copyA.data, copyA.shape[0]);
copyA.swapOrder();
return tril(copyA);
}
|
javascript
|
{
"resource": ""
}
|
q8810
|
lstsq
|
train
|
function lstsq(A, B, rcond) {
if (rcond === void 0) { rcond = -1; }
var copyA = A.clone();
var copyB = B.clone();
var is_1d = false;
if (copyB.shape.length === 1) {
copyB.reshape([copyB.shape[0], 1]);
is_1d = true;
}
var m;
var n;
m = copyA.shape[0];
n = copyA.shape[1];
var nrhs = copyB.shape[1];
copyA.swapOrder();
copyB.swapOrder();
var S = new common_1.NDArray({ shape: [Math.min(m, n)] });
var rank = lapack.gelsd(copyA.data, m, n, nrhs, rcond, copyB.data, S.data);
copyB.swapOrder();
// Residuals - TODO: test more
var residuals = new common_1.NDArray([]);
if (rank === n && m > n) {
var i = void 0;
if (is_1d) {
residuals = new common_1.NDArray({ shape: [1] });
var sum = 0;
for (i = n; i < m; i++) {
var K = copyB.shape[1];
for (var j = 0; j < K; j++) {
// TODO:Complex
sum += copyB.get(i, j) * copyB.get(i, j);
}
}
residuals.set(0, sum);
}
else {
residuals = new common_1.NDArray({ shape: [m - n] });
for (i = n; i < m; i++) {
var K = copyB.shape[1];
var sum = 0;
for (var j = 0; j < K; j++) {
// TODO:Complex
sum += copyB.get(i, j) * copyB.get(i, j);
}
residuals.set(i - n, sum);
}
}
}
return {
x: copyB,
residuals: residuals,
rank: rank,
singulars: S
};
}
|
javascript
|
{
"resource": ""
}
|
q8811
|
slogdet
|
train
|
function slogdet(A) {
if (A.shape.length !== 2) {
throw new Error('Input is not matrix');
}
if (A.shape[0] !== A.shape[1]) {
throw new Error('Input is not square matrix');
}
var m = A.shape[0];
var copyA = A.clone();
copyA.swapOrder();
var ipiv = new common_1.NDArray({ shape: [m], datatype: 'i32' });
lapack.getrf(copyA.data, m, m, ipiv.data);
copyA.swapOrder();
// Multiply diagonal elements of Upper triangular matrix to get determinant
// For large matrices this value could get really big, hence we add
// natural logarithms of the diagonal elements and save the sign
// separately
var sign_acc = 1;
var log_acc = 0;
// Note: The pivot vector affects the sign of the determinant
// I do not understand why, but this is what numpy implementation does
for (var i = 0; i < m; i++) {
if (ipiv.get(i) !== i + 1) {
sign_acc = -sign_acc;
}
}
for (var i = 0; i < m; i++) {
var e = copyA.get(i, i);
// TODO:Complex
var e_abs = Math.abs(e);
var e_sign = e / e_abs;
sign_acc *= e_sign;
log_acc += Math.log(e_abs);
}
return [sign_acc, log_acc];
}
|
javascript
|
{
"resource": ""
}
|
q8812
|
det
|
train
|
function det(A) {
var _a = slogdet(A), sign = _a[0], log = _a[1];
return sign * Math.exp(log);
}
|
javascript
|
{
"resource": ""
}
|
q8813
|
tril
|
train
|
function tril(A, k) {
if (k === void 0) { k = 0; }
if (A.shape.length !== 2) {
throw new Error('Input is not matrix');
}
var copyA = A.clone();
for (var i = 0; i < copyA.shape[0]; i++) {
for (var j = 0; j < copyA.shape[1]; j++) {
if (i < j - k) {
copyA.set(i, j, 0);
}
}
}
return copyA;
}
|
javascript
|
{
"resource": ""
}
|
q8814
|
qr
|
train
|
function qr(A) {
if (A.shape.length !== 2) {
throw new Error('Input is not matrix');
}
var _a = A.shape, m = _a[0], n = _a[1];
if (m === 0 || n === 0) {
throw new Error('Empty matrix');
}
var copyA = A.clone();
var minmn = Math.min(m, n);
copyA.swapOrder();
var tau = new common_1.NDArray({ shape: [minmn] });
lapack.geqrf(copyA.data, m, n, tau.data);
var r = copyA.clone();
r.swapOrder();
r = triu(r.get(':', ':' + minmn));
var q = copyA.get(':' + n);
lapack.orgqr(q.data, m, n, minmn, tau.data);
q.swapOrder();
return [q, r];
}
|
javascript
|
{
"resource": ""
}
|
q8815
|
eig
|
train
|
function eig(A) {
if (A.shape.length !== 2) {
throw new Error('Input is not matrix');
}
if (A.shape[0] !== A.shape[1]) {
throw new Error('Input is not square matrix');
}
var n = A.shape[0];
var copyA = A.clone();
copyA.swapOrder();
var _a = lapack.geev(copyA.data, n, true, true), WR = _a[0], WI = _a[1], VL = _a[2], VR = _a[3];
var eigval = new common_1.NDArray({ shape: [n] });
var eigvecL = new common_1.NDArray({ shape: [n, n] });
var eigvecR = new common_1.NDArray({ shape: [n, n] });
for (var i = 0; i < n; i++) {
if (common_1.iszero(WI[i])) {
eigval.set(i, WR[i]);
}
else {
eigval.set(i, new common_1.Complex(WR[i], WI[i]));
}
}
for (var i = 0; i < n; i++) {
for (var j = 0; j < n;) {
if (common_1.iszero(WI[j])) {
// We want to extract eigen-vectors in i'th column of VL and VR
eigvecL.set(i, j, VL[j * n + i]);
eigvecR.set(i, j, VR[j * n + i]);
j += 1;
}
else {
// i-th eigen vector will be complex and
// i+1-th eigen vector will be its conjugate
// There are n eigen-vectors for i'th eigen-value
eigvecL.set(i, j, new common_1.Complex(VL[j * n + i], VL[(j + 1) * n + i]));
eigvecL.set(i, j + 1, new common_1.Complex(VL[j * n + i], -VL[(j + 1) * n + i]));
eigvecR.set(i, j, new common_1.Complex(VR[j * n + i], VR[(j + 1) * n + i]));
eigvecR.set(i, j + 1, new common_1.Complex(VR[j * n + i], -VR[(j + 1) * n + i]));
j += 2;
}
}
}
return [eigval, eigvecL, eigvecR];
}
|
javascript
|
{
"resource": ""
}
|
q8816
|
processBreakpoint
|
train
|
function processBreakpoint(root, breakpointOption) {
if (breakpointOption && breakpointOption !== Object(breakpointOption)) {
throw new Error('Breakpoint must be of type Object.');
}
const processedBreakpoint = Object.assign({}, breakpointOption);
let atRule;
/* search current rules to see if one exists */
root.walkAtRules('media', rule => {
if (rule.params !== processedBreakpoint.mediaQuery) return;
atRule = rule;
});
/* if no rules exist, create a new one */
if (!atRule) {
atRule = postcss.atRule({
name: 'media',
params: processedBreakpoint.mediaQuery,
});
}
processedBreakpoint.atRule = atRule;
return processedBreakpoint;
}
|
javascript
|
{
"resource": ""
}
|
q8817
|
processBreakpoints
|
train
|
function processBreakpoints(root, breakpointsOption) {
if (breakpointsOption && !Array.isArray(breakpointsOption)) {
throw new Error('Breakpoints option must be of type Array.');
}
const defaultBreakpoints = [
{
prefix: 'xs-',
mediaQuery: '(max-width: 40em)',
},
{
prefix: 'sm-',
mediaQuery: '(min-width: 40em)',
},
{
prefix: 'md-',
mediaQuery: '(min-width: 52em)',
},
{
prefix: 'lg-',
mediaQuery: '(min-width: 64em)',
},
];
const mergedBreakpoints = merge([], defaultBreakpoints, breakpointsOption);
return mergedBreakpoints.map((breakpoint) => processBreakpoint(root, breakpoint));
}
|
javascript
|
{
"resource": ""
}
|
q8818
|
createPrefixedRule
|
train
|
function createPrefixedRule(rule, prefix) {
const prefixLength = prefix.length;
const selectorStart = rule.selector.slice(1, prefixLength + 1);
const isAlreadyPrefixed = selectorStart === prefix;
if (isAlreadyPrefixed) return false;
return rule.clone({
selector: `.${prefix + rule.selector.substring(1)}`,
});
}
|
javascript
|
{
"resource": ""
}
|
q8819
|
responsifyRule
|
train
|
function responsifyRule(breakpoints) {
/**
* Closure function that handles each @responsive sub rule
* @param {Object} rule
*/
return (rule) => {
/* insert the base rule right before the @responsive rule */
const root = rule.parent.parent;
const clone = rule.clone();
root.insertBefore(rule.parent, clone);
const isValidSelector = rule.selector.charAt(0) === '.';
if (!isValidSelector) return; /* equivilent to continue; */
/* insert each responsive rule in its breakpoint's atRule */
breakpoints.forEach((breakpoint) => {
const responsiveRule = createPrefixedRule(rule, breakpoint.prefix);
if (responsiveRule) {
breakpoint.atRule.append(responsiveRule);
}
});
};
}
|
javascript
|
{
"resource": ""
}
|
q8820
|
loopResponsiveRules
|
train
|
function loopResponsiveRules(breakpoints) {
/**
* Closure function that handles each @responsive atRule
* @param {Object} rule
*/
return (rule) => {
const subRules = rule.nodes;
subRules.forEach(responsifyRule(breakpoints));
/* remove the @responsive structure since we've built the responsive rules we need */
rule.remove();
};
}
|
javascript
|
{
"resource": ""
}
|
q8821
|
processDefinition
|
train
|
function processDefinition(definition) {
var fields = [];
var types = {};
var key;
var fieldDefinition;
var type;
for (key in definition) {
if (definition.hasOwnProperty(key)) {
fields.push(key);
fieldDefinition = definition[key];
type = determineType(fieldDefinition);
// Normalize the type definition
if (value(fieldDefinition).getConstructor() === Object) {
definition[key].type = type;
} else {
definition[key] = {
type: type
};
}
if (value(fieldDefinition).getConstructor() === Object) {
definition[key].writable = fieldDefinition.hasOwnProperty("writable") ? fieldDefinition.writable : true;
} else {
definition[key].writable = true;
}
if (value(fieldDefinition).getConstructor() === Object) {
definition[key].readable = fieldDefinition.hasOwnProperty("readable") ? fieldDefinition.readable : true;
} else {
definition[key].readable = true;
}
types[key] = type;
}
}
return {
fields: fields,
types: types
};
}
|
javascript
|
{
"resource": ""
}
|
q8822
|
findProcessWithIndex
|
train
|
function findProcessWithIndex( index, callback ) {
var i, process;
try {
forever.list(false, function(context, list) {
i = list ? list.length : 0;
while( --i > -1 ) {
process = list[i];
if( process.hasOwnProperty('file') &&
process.file === index ) {
break;
}
process = undefined;
}
callback.call(null, process);
});
}
catch( e ) {
error( 'Error in trying to find process ' + index + ' in forever. [REASON] :: ' + e.message );
callback.call(null, undefined);
}
}
|
javascript
|
{
"resource": ""
}
|
q8823
|
startForeverWithIndex
|
train
|
function startForeverWithIndex( index, doneCB ) {
log( 'Attempting to start ' + index + ' as daemon.');
var config;
var appendConfig = function(prop, value) {
log('Adding to config: ' + prop + ', ' + value);
if(value !== undefined) {
config[prop] = value;
}
};
done = doneCB || this.async();
findProcessWithIndex( index, function(process) {
// if found, be on our way without failing.
if( typeof process !== 'undefined' ) {
warn( index + ' is already running.');
log( forever.format(true, [process]) );
done();
}
else {
gruntRef.file.mkdir(logDir);
// 'forever start -o out.log -e err.log -c node -a -m 3 index.js';
config = {
command: commandName,
append: true,
max: 3,
killSignal: killSignal
};
appendConfig('errFile', errFile);
appendConfig('outFile', outFile);
appendConfig('logFile', logFile);
forever.startDaemon( index, config );
log( 'Logs can be found at ' + logDir + '.' );
done();
}
});
}
|
javascript
|
{
"resource": ""
}
|
q8824
|
stopOnProcess
|
train
|
function stopOnProcess(index) {
log( 'Attempting to stop ' + index + '...' );
done = this.async();
findProcessWithIndex( index, function(process) {
if( typeof process !== 'undefined' ) {
log( forever.format(true,[process]) );
forever.stop( index )
.on('stop', function() {
done();
})
.on('error', function(message) {
error( 'Error stopping ' + index + '. [REASON] :: ' + message );
done(false);
});
}
else {
gruntRef.warn( index + ' not found in list of processes in forever.' );
done();
}
});
}
|
javascript
|
{
"resource": ""
}
|
q8825
|
restartOnProcess
|
train
|
function restartOnProcess( index ) {
log( 'Attempting to restart ' + index + '...' );
// generate delegate function to pass with proper contexts.
var startRequest = (function(context, index) {
return function(cb) {
startForeverWithIndex.call(context, index, cb);
};
}(this, index));
done = this.async();
findProcessWithIndex( index, function(process) {
if(typeof process !== 'undefined') {
log(forever.format(true,[process]));
forever.restart(index, false);
done();
}
else {
log(index + ' not found in list of processes in forever. Starting new instance...');
startRequest(done);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q8826
|
train
|
function(target, source) {
if (!ES.TypeIsObject(target)) {
throw new TypeError('target must be an object');
}
return Array.prototype.reduce.call(arguments, function(target, source) {
if (!ES.TypeIsObject(source)) {
throw new TypeError('source must be an object');
}
return Object.keys(source).reduce(function(target, key) {
target[key] = source[key];
return target;
}, target);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q8827
|
train
|
function(C) {
if (!ES.IsCallable(C)) {
throw new TypeError('bad promise constructor');
}
var capability = this;
var resolver = function(resolve, reject) {
capability.resolve = resolve;
capability.reject = reject;
};
capability.promise = ES.Construct(C, [resolver]);
// see https://bugs.ecmascript.org/show_bug.cgi?id=2478
if (!capability.promise._es6construct) {
throw new TypeError('bad promise constructor');
}
if (!(ES.IsCallable(capability.resolve) &&
ES.IsCallable(capability.reject))) {
throw new TypeError('bad promise constructor');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q8828
|
Set
|
train
|
function Set() {
var set = this;
set = emulateES6construct(set);
if (!set._es6set) {
throw new TypeError('bad set');
}
defineProperties(set, {
'[[SetData]]': null,
'_storage': emptyObject()
});
// Optionally initialize map from iterable
var iterable = arguments[0];
if (iterable !== undefined && iterable !== null) {
var it = ES.GetIterator(iterable);
var adder = set.add;
if (!ES.IsCallable(adder)) { throw new TypeError('bad set'); }
while (true) {
var next = ES.IteratorNext(it);
if (next.done) { break; }
var nextItem = next.value;
adder.call(set, nextItem);
}
}
return set;
}
|
javascript
|
{
"resource": ""
}
|
q8829
|
ensureMap
|
train
|
function ensureMap(set) {
if (!set['[[SetData]]']) {
var m = set['[[SetData]]'] = new collectionShims.Map();
Object.keys(set._storage).forEach(function(k) {
// fast check for leading '$'
if (k.charCodeAt(0) === 36) {
k = k.substring(1);
} else {
k = +k;
}
m.set(k, k);
});
set._storage = null; // free old backing storage
}
}
|
javascript
|
{
"resource": ""
}
|
q8830
|
details
|
train
|
function details(id) {
return new Promise((resolve, reject) => {
if (!id || id === '') throw new Error('id cannot be blank');
const options = {
method: 'GET',
hostname: 'www.exploitalert.com',
port: null,
path: `/view-details.html?id=${id}`,
headers: {},
};
const req = http.request(options, (res) => {
const chunks = [];
res.on('data', (chunk) => {
chunks.push(chunk);
});
res.on('end', () => {
const body = Buffer.concat(chunks);
resolve(body.toString());
});
});
req.on('error', reject);
req.end();
})
.then((html) => {
const $ = cheerio.load(html);
return $('pre').text();
})
.catch(err => err);
}
|
javascript
|
{
"resource": ""
}
|
q8831
|
train
|
function(data_dir) {
var data_files = {}
var format = new RegExp("([0-9a-z\\-_]+)\\.(json|csv)$" , "i");
//see if there's a folder for partial data relating to this page or layout
//if so iterate all json/csv files and load the data
var partial_data_folder = data_dir + "/"+$type +"s/partials/" + $name;
var stats;
if(fs.existsSync(partial_data_folder) && (stats = fs.statSync(partial_data_folder)) && stats.isDirectory()) {
var files = fs.readdirSync(partial_data_folder)
files.forEach(function (name) {
var filename;//file name, which we use as the variable name
if (! (filename = name.match(format)) ) return;
data_files[filename[1]] = partial_data_folder + "/" + name;
})
}
for(var var_name in data_files) if(data_files.hasOwnProperty(var_name)) {
var new_data
try {
if(data_files[var_name].match(/\.json$/i)) {
new_data = fs.readFileSync(data_files[var_name] , 'utf-8');
new_data = JSON.parse(new_data);
} else if(data_files[var_name].match(/\.csv$/i)) {
//load csv data into an array
var csv_data = require(data_files[var_name]);
//now convert it to json
var csv_header = csv_data[0];
var length = csv_data.length;
var json_data = []
for(var i = 1 ; i < length; i++) {
var csv_row = csv_data[i];
var json_row = {}
for(var j = 0; j < csv_row.length; j++) {
json_row[csv_header[j]] = csv_row[j];
}
//for example if we have "status":"pending" , add this to it as well : "pending":true
if("status" in json_row) json_row[json_row["status"].toLowerCase()] = true;
json_data.push(json_row);
}
new_data = json_data
}
} catch(e) {
console.log("Invalid JSON Data File : " + data_files[var_name]);
continue;
}
$vars[var_name.replace(/\./g , '_')] = new_data
//here we replace '.' with '_' in variable names, so template compiler can recognize it as a variable not an object
//for example change sidebar.navList to sidebar_navList , because sidebar is not an object
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q8832
|
train
|
function (dt) {
_.each(
systems,
function (system) {
if (_.has(system, 'tickStart')) {
system.tickStart(dt);
}
}
);
}
|
javascript
|
{
"resource": ""
}
|
|
q8833
|
train
|
function (dt) {
_.each(
systems,
function (system) {
if (_.has(system, 'update')) {
_.each(
entities,
function (entity) {
if (!_.isUndefined(entity)) {
_.each(system.update, function (func, id) {
if (entity.has(id)){
func(entity, dt);
}
});
}
}
);
}
}
);
}
|
javascript
|
{
"resource": ""
}
|
|
q8834
|
train
|
function (dt) {
_.each(
systems,
function (system) {
if (_.has(system, 'tickEnd')) {
system.tickEnd(dt);
}
}
);
}
|
javascript
|
{
"resource": ""
}
|
|
q8835
|
train
|
function (entity, just) {
_.each(
systems,
function (system) {
if (_.has(system, 'destroy')) {
_.each(system.destroy, function (func, id) {
if (entity.has(id)){
// Only remove from tracking systems.
if (!_.isUndefined(just)) {
if (id !== just) {
return;
}
}
// Perform the remove.
func(entity);
}
});
}
}
);
}
|
javascript
|
{
"resource": ""
}
|
|
q8836
|
train
|
function(piece, quote_char) {
// Matches everything that is not a quote or \
var regex = new RegExp("[^" + quote_char + "\\\\]", 'g');
// Remove eveything that is not quote or \
var replaced = piece.replace(regex, '');
// Remove escaped quotes, then remove all remaining slashes, then count.
return replaced.replace(
new RegExp('(\\\\' + quote_char + ')', 'g'), ''
).replace(
/\\/g, ''
).length;
}
|
javascript
|
{
"resource": ""
}
|
|
q8837
|
train
|
function(piece, quote_char, position = 0) {
var i = position - 1; //-1 because we're incrementing it
do {
i = piece.indexOf(quote_char, i+1);
} while(piece.charAt(i-1) === '\\');
return i;
}
|
javascript
|
{
"resource": ""
}
|
|
q8838
|
train
|
function(pieces, quote_char) {
var unclosed_quote = false;
var result = [];
for (var i = 0; i < pieces.length; i++) {
if (unclosed_quote) {
// Two scenarios. Either we have a closing quote or we don't.
if (hasQuote(pieces[i], quote_char)) {
// If it does, then there are two scenarios again:
// Either the closing quote is the last character,
// or there is text after it.
var q_index = getFirstQuote(pieces[i], quote_char);
if (q_index !== (pieces[i].length - 1)) {
// The closing quote is not the last character; there's text after it.
// We take that text and put it on the next piece.
pieces[i+1] =
pieces[i].substring(q_index + 1, pieces[i].length)
+ (typeof pieces[i+1] !== 'undefined'
? pieces[i+1] : '');
pieces[i] = pieces[i].substring(0, q_index+1);
}
// Now the two scenarios are reduced to one. The last character of the
// current piece will always be the last. We can now conclude that the
// unclosed quote is now closed.
result[result.length-1] =
result[result.length-1] + ' ' + pieces[i];
unclosed_quote = false;
} else {
// We don't have a closing quote. That means that the current piece is part
// of the current string. So we concatenate it to the last piece in
// result
result[result.length-1] =
result[result.length-1] + ' ' + pieces[i];
}
} else {
// Two scenarios. Either we have an opening quote or we don't.
if (hasQuote(pieces[i], quote_char)) {
// We have an opening quote.
// Three scenarios. We have one, two, or more than two
if (countQuotes(pieces[i], quote_char) === 1) {
// We have just one opening quote. We can safely add this piece to the
// good pieces and carry on iterating. Any further pieces will be
// concatenated with this one until the unclosed_quote gets closed.
result.push(pieces[i]);
unclosed_quote = true;
} else if (countQuotes(pieces[i], quote_char) === 2) {
// We have two quotes. However, we might have information after the
// closing quote that doesn't belong to the string, so we split:
var split = splitPiece(pieces[i], quote_char);
// Both parts are safe to push, but we make sure that part 2 exists.
result.push(split[0]);
if(split[1] !== '') result.push(split[1]);
} else {
// We have more than three quotes. We split them. The first part of
// each split is always safe to store in result because it's a full
// closed string. The second part can be on any of the three scenarios:
// one, two or three quotes. So we keep iterating until it's on the
// first or on the second.
var next = pieces[i];
do {
var split = splitPiece(next, quote_char);
result.push(split[0]);
next = split[1];
} while (countQuotes(next, quote_char) > 2);
// Now, the string that's left is in scenario 1 or 2.
// We follow the same procedure.
if(countQuotes(next, quote_char) === 1) {
result.push(next);
unclosed_quote = true;
} else if (countQuotes(next, quote_char) === 2) {
result.push(next);
} else {
// This shouldn't happen.
throw new Error('I\'m sorry, but minimist-string has encountered' +
'unexpected behaviour. This is porbably not your fault and' +
'just a bug. Please report it with the stack trace on the' +
'GitHub tracker.');
}
}
} else {
// We don't have a quote on this piece.
// We can safely move on to the next one.
result.push(pieces[i]);
}
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
|
q8839
|
runPngquant
|
train
|
function runPngquant(args, callback) {
grunt.log.debug('Trying to spawn "' + options.binary + '" with arguments: ');
grunt.log.debug(args.join(' '));
grunt.util.spawn({
cmd: options.binary,
args: args
}, callback);
}
|
javascript
|
{
"resource": ""
}
|
q8840
|
addOrSubtractDurationFromMoment
|
train
|
function addOrSubtractDurationFromMoment(mom, duration, isAdding) {
var ms = duration._milliseconds,
d = duration._days,
M = duration._months,
currentDate;
if (ms) {
mom._d.setTime(+mom + ms * isAdding);
}
if (d) {
mom.date(mom.date() + d * isAdding);
}
if (M) {
currentDate = mom.date();
mom.date(1)
.month(mom.month() + M * isAdding)
.date(Math.min(currentDate, mom.daysInMonth()));
}
}
|
javascript
|
{
"resource": ""
}
|
q8841
|
train
|
function (config, loggerContext) {
config = config || {};
Layout.call(this, config, loggerContext);
this.compact = config.compact || false;
this.depth = config.depth || 2;
this.messageAsObject = config.messageAsObject || false;
}
|
javascript
|
{
"resource": ""
}
|
|
q8842
|
requestHandlerComposer
|
train
|
function requestHandlerComposer(componentMap) {
const buildTemplateData = buildTemplateDataComposer(componentMap);
/**
* @async
* @callback {handler}
*
* Handles an incoming request to a Hapi route configured by a Windshield server.
* The request is handled with by using Windshield to produce a Handlebars
* template and a set of template source data, which are then passing into the
* Hapi Vision plugin to generate an HTML response.
*
* @param {Request} request - The Hapi request object
* @param {Toolkit} h - The Hapi response toolkit
* @returns {Promise<Response>} Promise that resolves with the response
*/
return async function handler(request, h) {
try {
const {template, data} = await buildTemplateData(request);
// The Hapi vision plugin adds the view() method to the response toolkit
const visionResponse = h.view(template, data);
const headers = data.attributes.headers || {};
// add headers to the response object one by one
return Object.entries(headers).reduce((vResponse, [key, value]) => {
return vResponse.header(key, value);
}, visionResponse);
} catch (err) {
request.server.log('error', err);
if (process.env.NODE_ENV === 'production') {
return err;
}
const errMsg = err.stack.replace(/\n/g, "<br>").replace(/ /g, " ");
return h.response(errMsg).code(500);
}
};
}
|
javascript
|
{
"resource": ""
}
|
q8843
|
baseCompareAscending
|
train
|
function baseCompareAscending(value, other) {
if (value !== other) {
if (value > other || typeof value == 'undefined') {
return 1;
}
if (value < other || typeof other == 'undefined') {
return -1;
}
}
return 0;
}
|
javascript
|
{
"resource": ""
}
|
q8844
|
compareMultipleAscending
|
train
|
function compareMultipleAscending(object, other) {
var index = -1,
objCriteria = object.criteria,
othCriteria = other.criteria,
length = objCriteria.length;
while (++index < length) {
var result = baseCompareAscending(objCriteria[index], othCriteria[index]);
if (result) {
return result;
}
}
// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
// that causes it, under certain circumstances, to provide the same value
// for `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
//
// This also ensures a stable sort in V8 and other engines.
// See https://code.google.com/p/v8/issues/detail?id=90
return object.index - other.index;
}
|
javascript
|
{
"resource": ""
}
|
q8845
|
arrayEachRight
|
train
|
function arrayEachRight(array, callback) {
var length = array ? array.length : 0;
while (length--) {
if (callback(array[length], length, array) === false) {
break;
}
}
return array;
}
|
javascript
|
{
"resource": ""
}
|
q8846
|
arrayMap
|
train
|
function arrayMap(array, callback) {
var index = -1,
length = array ? array.length >>> 0 : 0,
result = Array(length);
while (++index < length) {
result[index] = callback(array[index], index, array);
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q8847
|
baseClone
|
train
|
function baseClone(value, isDeep, callback, stackA, stackB) {
if (callback) {
var result = callback(value);
if (typeof result != 'undefined') {
return result;
}
}
var isObj = isObject(value);
if (isObj) {
var className = toString.call(value);
if (!cloneableClasses[className]) {
return value;
}
var ctor = ctorByClass[className];
switch (className) {
case boolClass:
case dateClass:
return new ctor(+value);
case numberClass:
case stringClass:
return new ctor(value);
case regexpClass:
result = ctor(value.source, reFlags.exec(value));
result.lastIndex = value.lastIndex;
return result;
}
} else {
return value;
}
var isArr = isArray(value);
if (isDeep) {
// check for circular references and return corresponding clone
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == value) {
return stackB[length];
}
}
result = isArr ? ctor(value.length) : {};
}
else {
result = isArr ? slice(value) : assign({}, value);
}
// add array properties assigned by `RegExp#exec`
if (isArr) {
if (hasOwnProperty.call(value, 'index')) {
result.index = value.index;
}
if (hasOwnProperty.call(value, 'input')) {
result.input = value.input;
}
}
// exit for shallow clone
if (!isDeep) {
return result;
}
// add the source value to the stack of traversed objects
// and associate it with its clone
stackA.push(value);
stackB.push(result);
// recursively populate clone (susceptible to call stack limits)
(isArr ? arrayEach : baseForOwn)(value, function(valValue, key) {
result[key] = baseClone(valValue, isDeep, callback, stackA, stackB);
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q8848
|
baseEach
|
train
|
function baseEach(collection, callback) {
var index = -1,
iterable = collection,
length = collection ? collection.length : 0;
if (typeof length == 'number' && length > -1 && length <= maxSafeInteger) {
while (++index < length) {
if (callback(iterable[index], index, collection) === false) {
break;
}
}
} else {
baseForOwn(collection, callback);
}
return collection;
}
|
javascript
|
{
"resource": ""
}
|
q8849
|
baseEachRight
|
train
|
function baseEachRight(collection, callback) {
var iterable = collection,
length = collection ? collection.length : 0;
if (typeof length == 'number' && length > -1 && length <= maxSafeInteger) {
while (length--) {
if (callback(iterable[length], length, collection) === false) {
break;
}
}
} else {
baseForOwnRight(collection, callback);
}
return collection;
}
|
javascript
|
{
"resource": ""
}
|
q8850
|
baseFor
|
train
|
function baseFor(object, callback, keysFunc) {
var index = -1,
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
|
javascript
|
{
"resource": ""
}
|
q8851
|
baseForRight
|
train
|
function baseForRight(object, callback, keysFunc) {
var props = keysFunc(object),
length = props.length;
while (length--) {
var key = props[length];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
|
javascript
|
{
"resource": ""
}
|
q8852
|
baseUniq
|
train
|
function baseUniq(array, isSorted, callback) {
var length = array ? array.length : 0;
if (!length) {
return [];
}
var index = -1,
indexOf = getIndexOf(),
prereq = !isSorted && indexOf === baseIndexOf,
isLarge = prereq && createCache && length >= 200,
isCommon = prereq && !isLarge,
result = [];
if (isLarge) {
var seen = createCache();
indexOf = cacheIndexOf;
} else {
seen = (callback && !isSorted) ? [] : result;
}
outer:
while (++index < length) {
var value = array[index],
computed = callback ? callback(value, index, array) : value;
if (isCommon) {
var seenIndex = seen.length;
while (seenIndex--) {
if (seen[seenIndex] === computed) {
continue outer;
}
}
if (callback) {
seen.push(computed);
}
result.push(value);
}
else if (isSorted) {
if (!index || seen !== computed) {
seen = computed;
result.push(value);
}
}
else if (indexOf(seen, computed) < 0) {
if (callback || isLarge) {
seen.push(computed);
}
result.push(value);
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q8853
|
createAggregator
|
train
|
function createAggregator(setter, initializer) {
return function(collection, callback, thisArg) {
var result = initializer ? initializer() : {};
callback = lodash.createCallback(callback, thisArg, 3);
var index = -1,
length = collection ? collection.length : 0;
if (typeof length == 'number' && length > -1 && length <= maxSafeInteger) {
while (++index < length) {
var value = collection[index];
setter(result, value, callback(value, index, collection), collection);
}
} else {
baseEach(collection, function(value, key, collection) {
setter(result, value, callback(value, key, collection), collection);
});
}
return result;
};
}
|
javascript
|
{
"resource": ""
}
|
q8854
|
createPad
|
train
|
function createPad(string, length, chars) {
var strLength = string.length;
length = +length;
if (strLength >= length || !nativeIsFinite(length)) {
return '';
}
var padLength = length - strLength;
chars = chars == null ? ' ' : String(chars);
return repeat(chars, ceil(padLength / chars.length)).slice(0, padLength);
}
|
javascript
|
{
"resource": ""
}
|
q8855
|
createWrapper
|
train
|
function createWrapper(func, bitmask, arity, thisArg, partialArgs, partialRightArgs) {
var isBind = bitmask & BIND_FLAG,
isBindKey = bitmask & BIND_KEY_FLAG,
isPartial = bitmask & PARTIAL_FLAG,
isPartialRight = bitmask & PARTIAL_RIGHT_FLAG;
if (!isBindKey && !isFunction(func)) {
throw new TypeError(funcErrorText);
}
if (isPartial && !partialArgs.length) {
bitmask &= ~PARTIAL_FLAG;
isPartial = partialArgs = false;
}
if (isPartialRight && !partialRightArgs.length) {
bitmask &= ~PARTIAL_RIGHT_FLAG;
isPartialRight = partialRightArgs = false;
}
var data = !isBindKey && func[expando];
if (data && data !== true) {
// shallow clone `data`
data = slice(data);
// clone partial left arguments
if (data[4]) {
data[4] = slice(data[4]);
}
// clone partial right arguments
if (data[5]) {
data[5] = slice(data[5]);
}
// set arity if provided
if (typeof arity == 'number') {
data[2] = arity;
}
// set `thisArg` if not previously bound
var bound = data[1] & BIND_FLAG;
if (isBind && !bound) {
data[3] = thisArg;
}
// set if currying a bound function
if (!isBind && bound) {
bitmask |= CURRY_BOUND_FLAG;
}
// append partial left arguments
if (isPartial) {
if (data[4]) {
push.apply(data[4], partialArgs);
} else {
data[4] = partialArgs;
}
}
// prepend partial right arguments
if (isPartialRight) {
if (data[5]) {
unshift.apply(data[5], partialRightArgs);
} else {
data[5] = partialRightArgs;
}
}
// merge flags
data[1] |= bitmask;
return createWrapper.apply(null, data);
}
if (isPartial) {
var partialHolders = [];
}
if (isPartialRight) {
var partialRightHolders = [];
}
if (arity == null) {
arity = isBindKey ? 0 : func.length;
}
arity = nativeMax(arity, 0);
// fast path for `_.bind`
data = [func, bitmask, arity, thisArg, partialArgs, partialRightArgs, partialHolders, partialRightHolders];
return (bitmask == BIND_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG))
? baseBind(data)
: baseCreateWrapper(data);
}
|
javascript
|
{
"resource": ""
}
|
q8856
|
shimKeys
|
train
|
function shimKeys(object) {
var keyIndex,
index = -1,
props = keysIn(object),
length = props.length,
objLength = length && object.length,
maxIndex = objLength - 1,
result = [];
var allowIndexes = typeof objLength == 'number' && objLength > 0 &&
(isArray(object) || (support.nonEnumArgs && isArguments(object)));
while (++index < length) {
var key = props[index];
if ((allowIndexes && (keyIndex = +key, keyIndex > -1 && keyIndex <= maxIndex && keyIndex % 1 == 0)) ||
hasOwnProperty.call(object, key)) {
result.push(key);
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q8857
|
findIndex
|
train
|
function findIndex(array, predicate, thisArg) {
var index = -1,
length = array ? array.length : 0;
predicate = lodash.createCallback(predicate, thisArg, 3);
while (++index < length) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
|
javascript
|
{
"resource": ""
}
|
q8858
|
rest
|
train
|
function rest(array, predicate, thisArg) {
if (typeof predicate != 'number' && predicate != null) {
var index = -1,
length = array ? array.length : 0,
n = 0;
predicate = lodash.createCallback(predicate, thisArg, 3);
while (++index < length && predicate(array[index], index, array)) {
n++;
}
} else if (predicate == null || thisArg) {
n = 1;
} else {
n = predicate < 0 ? 0 : predicate;
}
return slice(array, n);
}
|
javascript
|
{
"resource": ""
}
|
q8859
|
slice
|
train
|
function slice(array, start, end) {
var index = -1,
length = array ? array.length : 0;
start = typeof start == 'undefined' ? 0 : (+start || 0);
if (start < 0) {
start = nativeMax(length + start, 0);
} else if (start > length) {
start = length;
}
end = typeof end == 'undefined' ? length : (+end || 0);
if (end < 0) {
end = nativeMax(length + end, 0);
} else if (end > length) {
end = length;
}
length = start > end ? 0 : (end - start);
var result = Array(length);
while (++index < length) {
result[index] = array[start + index];
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q8860
|
size
|
train
|
function size(collection) {
var length = collection ? collection.length : 0;
return (typeof length == 'number' && length > -1 && length <= maxSafeInteger)
? length
: keys(collection).length;
}
|
javascript
|
{
"resource": ""
}
|
q8861
|
toArray
|
train
|
function toArray(collection) {
var length = collection && collection.length;
if (typeof length == 'number' && length > -1 && length <= maxSafeInteger) {
return slice(collection);
}
return values(collection);
}
|
javascript
|
{
"resource": ""
}
|
q8862
|
delay
|
train
|
function delay(func, wait) {
if (!isFunction(func)) {
throw new TypeError(funcErrorText);
}
var args = slice(arguments, 2);
return setTimeout(function() { func.apply(undefined, args); }, wait);
}
|
javascript
|
{
"resource": ""
}
|
q8863
|
once
|
train
|
function once(func) {
var ran,
result;
if (!isFunction(func)) {
throw new TypeError(funcErrorText);
}
return function() {
if (ran) {
return result;
}
ran = true;
result = func.apply(this, arguments);
// clear the `func` variable so the function may be garbage collected
func = null;
return result;
};
}
|
javascript
|
{
"resource": ""
}
|
q8864
|
findKey
|
train
|
function findKey(object, predicate, thisArg) {
predicate = lodash.createCallback(predicate, thisArg, 3);
return baseFind(object, predicate, baseForOwn, true);
}
|
javascript
|
{
"resource": ""
}
|
q8865
|
isArguments
|
train
|
function isArguments(value) {
return (value && typeof value == 'object' && typeof value.length == 'number' &&
toString.call(value) == argsClass) || false;
}
|
javascript
|
{
"resource": ""
}
|
q8866
|
isEmpty
|
train
|
function isEmpty(value) {
var result = true;
if (!value) {
return result;
}
var length = value.length;
if ((length > -1 && length <= maxSafeInteger) &&
(isArray(value) || isString(value) || isArguments(value) ||
(typeof value == 'object' && isFunction(value.splice)))) {
return !length;
}
baseForOwn(value, function() {
return (result = false);
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q8867
|
endsWith
|
train
|
function endsWith(string, target, position) {
string = string == null ? '' : String(string);
target = String(target);
var length = string.length;
position = (typeof position == 'undefined' ? length : nativeMin(position < 0 ? 0 : (+position || 0), length)) - target.length;
return position >= 0 && string.indexOf(target, position) == position;
}
|
javascript
|
{
"resource": ""
}
|
q8868
|
pad
|
train
|
function pad(string, length, chars) {
string = string == null ? '' : String(string);
length = +length;
var strLength = string.length;
if (strLength >= length || !nativeIsFinite(length)) {
return string;
}
var mid = (length - strLength) / 2,
leftLength = floor(mid),
rightLength = ceil(mid);
chars = createPad('', rightLength, chars);
return chars.slice(0, leftLength) + string + chars;
}
|
javascript
|
{
"resource": ""
}
|
q8869
|
padLeft
|
train
|
function padLeft(string, length, chars) {
string = string == null ? '' : String(string);
return createPad(string, length, chars) + string;
}
|
javascript
|
{
"resource": ""
}
|
q8870
|
padRight
|
train
|
function padRight(string, length, chars) {
string = string == null ? '' : String(string);
return string + createPad(string, length, chars);
}
|
javascript
|
{
"resource": ""
}
|
q8871
|
template
|
train
|
function template(string, data, options) {
// based on John Resig's `tmpl` implementation
// http://ejohn.org/blog/javascript-micro-templating/
// and Laura Doktorova's doT.js
// https://github.com/olado/doT
var settings = lodash.templateSettings;
options = defaults({}, options, settings);
string = String(string == null ? '' : string);
var imports = defaults({}, options.imports, settings.imports),
importsKeys = keys(imports),
importsValues = values(imports);
var isEscaping,
isEvaluating,
index = 0,
interpolate = options.interpolate || reNoMatch,
source = "__p += '";
// compile the regexp to match each delimiter
var reDelimiters = RegExp(
(options.escape || reNoMatch).source + '|' +
interpolate.source + '|' +
(interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
(options.evaluate || reNoMatch).source + '|$'
, 'g');
string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
interpolateValue || (interpolateValue = esTemplateValue);
// escape characters that cannot be included in string literals
source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
// replace delimiters with snippets
if (escapeValue) {
isEscaping = true;
source += "' +\n__e(" + escapeValue + ") +\n'";
}
if (evaluateValue) {
isEvaluating = true;
source += "';\n" + evaluateValue + ";\n__p += '";
}
if (interpolateValue) {
source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
}
index = offset + match.length;
// the JS engine embedded in Adobe products requires returning the `match`
// string in order to produce the correct `offset` value
return match;
});
source += "';\n";
// if `variable` is not specified, wrap a with-statement around the generated
// code to add the data object to the top of the scope chain
var variable = options.variable;
if (!variable) {
source = 'with (obj) {\n' + source + '\n}\n';
}
// cleanup code by stripping empty strings
source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
.replace(reEmptyStringMiddle, '$1')
.replace(reEmptyStringTrailing, '$1;');
// frame code as the function body
source = 'function(' + (variable || 'obj') + ') {\n' +
(variable
? ''
: 'obj || (obj = {});\n'
) +
"var __t, __p = ''" +
(isEscaping
? ', __e = _.escape'
: ''
) +
(isEvaluating
? ', __j = Array.prototype.join;\n' +
"function print() { __p += __j.call(arguments, '') }\n"
: ';\n'
) +
source +
'return __p\n}';
// Use a `sourceURL` for easier debugging.
// http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
var sourceURL = '\n/*\n//# sourceURL=' + (options.sourceURL || '/lodash/template/source[' + (templateCounter++) + ']') + '\n*/';
try {
var result = Function(importsKeys, 'return ' + source + sourceURL).apply(undefined, importsValues);
} catch(e) {
e.source = source;
throw e;
}
if (data) {
return result(data);
}
// provide the compiled function's source by its `toString` method, in
// supported environments, or the `source` property as a convenience for
// inlining compiled templates during the build process
result.source = source;
return result;
}
|
javascript
|
{
"resource": ""
}
|
q8872
|
truncate
|
train
|
function truncate(string, options) {
var length = 30,
omission = '...';
if (options && isObject(options)) {
var separator = 'separator' in options ? options.separator : separator;
length = 'length' in options ? +options.length || 0 : length;
omission = 'omission' in options ? String(options.omission) : omission;
}
else if (options != null) {
length = +options || 0;
}
string = string == null ? '' : String(string);
if (length >= string.length) {
return string;
}
var end = length - omission.length;
if (end < 1) {
return omission;
}
var result = string.slice(0, end);
if (separator == null) {
return result + omission;
}
if (isRegExp(separator)) {
if (string.slice(end).search(separator)) {
var match,
newEnd,
substring = string.slice(0, end);
if (!separator.global) {
separator = RegExp(separator.source, (reFlags.exec(separator) || '') + 'g');
}
separator.lastIndex = 0;
while ((match = separator.exec(substring))) {
newEnd = match.index;
}
result = result.slice(0, newEnd == null ? end : newEnd);
}
} else if (string.indexOf(separator, end) != end) {
var index = result.lastIndexOf(separator);
if (index > -1) {
result = result.slice(0, index);
}
}
return result + omission;
}
|
javascript
|
{
"resource": ""
}
|
q8873
|
createCallback
|
train
|
function createCallback(func, thisArg, argCount) {
var type = typeof func;
if (type == 'function' || func == null) {
return (typeof thisArg == 'undefined' || !('prototype' in func)) &&
func || baseCreateCallback(func, thisArg, argCount);
}
// handle "_.pluck" and "_.where" style callback shorthands
return type == 'object' ? matches(func) : property(func);
}
|
javascript
|
{
"resource": ""
}
|
q8874
|
matches
|
train
|
function matches(source) {
var props = keys(source),
propsLength = props.length,
key = props[0],
value = propsLength && source[key];
// fast path the common case of providing an object with a single
// property containing a primitive value
if (propsLength == 1 && value === value && !isObject(value)) {
return function(object) {
if (!(object && hasOwnProperty.call(object, key))) {
return false;
}
// treat `-0` vs. `+0` as not equal
var other = object[key];
return value === other && (value !== 0 || (1 / value == 1 / other));
};
}
return function(object) {
var length = propsLength;
if (length && !object) {
return false;
}
var result = true;
while (length--) {
var key = props[length];
if (!(result = hasOwnProperty.call(object, key) &&
baseIsEqual(object[key], source[key], null, true))) {
break;
}
}
return result;
};
}
|
javascript
|
{
"resource": ""
}
|
q8875
|
train
|
function(line) {
return {
'id': Number(line[0]),
'geoname_id': Number(line[1]),
'isolanguage': String(line[2]),
'alternate_name': String(line[3]),
'is_preferred': Boolean(line[4]),
'is_short': Boolean(line[5]),
'is_colloquial': Boolean(line[5]),
'is_historic': Boolean(line[6]),
};
}
|
javascript
|
{
"resource": ""
}
|
|
q8876
|
train
|
function(line) {
return {
'name': String(line[1]),
'country_code': String(line[0]),
'gmt_offset': Number(line[2]),
'dst_offset': Number(line[3]),
'raw_offset': Number(line[4])
};
}
|
javascript
|
{
"resource": ""
}
|
|
q8877
|
train
|
function(line) {
return {
'iso': String(line[0]),
'iso3': String(line[1]),
'iso_numeric': Number(line[2]),
'fips': String(line[3]),
'name': String(line[4]),
'capital': String(line[5]),
'area': Number(line[6]),
'population': Number(line[7]),
'continent': String(line[8]),
'tld': String(line[9]),
'currency_code': String(line[10]),
'currency_name': String(line[11]),
'phone': String(line[12]),
'postal_code_format': String(line[13]),
'postal_code_regex': String(line[14]),
'languages': String(line[15]),
'geoname_id': Number(line[16])
};
}
|
javascript
|
{
"resource": ""
}
|
|
q8878
|
train
|
function(name) {
var cookie = document.cookie, e, p = name + "=", b;
if ( !cookie )
return;
b = cookie.indexOf("; " + p);
if ( b == -1 ) {
b = cookie.indexOf(p);
if ( b != 0 )
return null;
} else {
b += 2;
}
e = cookie.indexOf(";", b);
if ( e == -1 )
e = cookie.length;
return decodeURIComponent( cookie.substring(b + p.length, e) );
}
|
javascript
|
{
"resource": ""
}
|
|
q8879
|
determineType
|
train
|
function determineType(obj) {
var type;
var typeValue;
var name;
if (value(obj).typeOf(Object)) {
type = obj.type || "Object";
} else {
type = obj;
}
typeValue = value(type);
if (typeValue.typeOf(String)) {
name = type.charAt(0).toUpperCase() + type.substring(1);
return supportedTypes.indexOf(name) === -1 ? "String" : name;
} else if (typeValue.typeOf(Function)) {
name = type.toString().match(fnName)[1];
} else if (typeValue.typeOf(Object)) {
if (type.type) {
name = type.type;
} else {
return "Object";
}
} else {
name = type.constructor.toString().match(fnName)[1];
}
if (supportedTypes.indexOf(name) === -1) {
throw new TypeError("Type '" + name + "' is not supported");
}
return name;
}
|
javascript
|
{
"resource": ""
}
|
q8880
|
buildSlotSegLevels
|
train
|
function buildSlotSegLevels(segs) {
var levels = [];
var i, seg;
var j;
for (i=0; i<segs.length; i++) {
seg = segs[i];
// go through all the levels and stop on the first level where there are no collisions
for (j=0; j<levels.length; j++) {
if (!computeSlotSegCollisions(seg, levels[j]).length) {
break;
}
}
(levels[j] || (levels[j] = [])).push(seg);
}
return levels;
}
|
javascript
|
{
"resource": ""
}
|
q8881
|
computeForwardSlotSegs
|
train
|
function computeForwardSlotSegs(levels) {
var i, level;
var j, seg;
var k;
for (i=0; i<levels.length; i++) {
level = levels[i];
for (j=0; j<level.length; j++) {
seg = level[j];
seg.forwardSegs = [];
for (k=i+1; k<levels.length; k++) {
computeSlotSegCollisions(seg, levels[k], seg.forwardSegs);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q8882
|
flattenSlotSegLevels
|
train
|
function flattenSlotSegLevels(levels) {
var segs = [];
var i, level;
var j;
for (i=0; i<levels.length; i++) {
level = levels[i];
for (j=0; j<level.length; j++) {
segs.push(level[j]);
}
}
return segs;
}
|
javascript
|
{
"resource": ""
}
|
q8883
|
computeSlotSegCollisions
|
train
|
function computeSlotSegCollisions(seg, otherSegs, results) {
results = results || [];
for (var i=0; i<otherSegs.length; i++) {
if (isSlotSegCollision(seg, otherSegs[i])) {
results.push(otherSegs[i]);
}
}
return results;
}
|
javascript
|
{
"resource": ""
}
|
q8884
|
isSlotSegCollision
|
train
|
function isSlotSegCollision(seg1, seg2) {
return seg1.end > seg2.start && seg1.start < seg2.end;
}
|
javascript
|
{
"resource": ""
}
|
q8885
|
compareForwardSlotSegs
|
train
|
function compareForwardSlotSegs(seg1, seg2) {
// put higher-pressure first
return seg2.forwardPressure - seg1.forwardPressure ||
// put segments that are closer to initial edge first (and favor ones with no coords yet)
(seg1.backwardCoord || 0) - (seg2.backwardCoord || 0) ||
// do normal sorting...
compareSlotSegs(seg1, seg2);
}
|
javascript
|
{
"resource": ""
}
|
q8886
|
eventElementHandlers
|
train
|
function eventElementHandlers(event, eventElement) {
eventElement
.click(function(ev) {
if (!eventElement.hasClass('ui-draggable-dragging') &&
!eventElement.hasClass('ui-resizable-resizing')) {
return trigger('eventClick', this, event, ev);
}
})
.hover(
function(ev) {
trigger('eventMouseover', this, event, ev);
},
function(ev) {
trigger('eventMouseout', this, event, ev);
}
);
// TODO: don't fire eventMouseover/eventMouseout *while* dragging is occuring (on subject element)
// TODO: same for resizing
}
|
javascript
|
{
"resource": ""
}
|
q8887
|
cellOffsetToDayOffset
|
train
|
function cellOffsetToDayOffset(cellOffset) {
var day0 = t.visStart.getDay(); // first date's day of week
cellOffset += dayToCellMap[day0]; // normlize cellOffset to beginning-of-week
return Math.floor(cellOffset / cellsPerWeek) * 7 // # of days from full weeks
+ cellToDayMap[ // # of days from partial last week
(cellOffset % cellsPerWeek + cellsPerWeek) % cellsPerWeek // crazy math to handle negative cellOffsets
]
- day0; // adjustment for beginning-of-week normalization
}
|
javascript
|
{
"resource": ""
}
|
q8888
|
dayOffsetToCellOffset
|
train
|
function dayOffsetToCellOffset(dayOffset) {
var day0 = t.visStart.getDay(); // first date's day of week
dayOffset += day0; // normalize dayOffset to beginning-of-week
return Math.floor(dayOffset / 7) * cellsPerWeek // # of cells from full weeks
+ dayToCellMap[ // # of cells from partial last week
(dayOffset % 7 + 7) % 7 // crazy math to handle negative dayOffsets
]
- dayToCellMap[day0]; // adjustment for beginning-of-week normalization
}
|
javascript
|
{
"resource": ""
}
|
q8889
|
renderTempDayEvent
|
train
|
function renderTempDayEvent(event, adjustRow, adjustTop) {
// actually render the event. `true` for appending element to container.
// Recieve the intermediate "segment" data structures.
var segments = _renderDayEvents(
[ event ],
true, // append event elements
false // don't set the heights of the rows
);
var elements = [];
// Adjust certain elements' top coordinates
segmentElementEach(segments, function(segment, element) {
if (segment.row === adjustRow) {
element.css('top', adjustTop);
}
elements.push(element[0]); // accumulate DOM nodes
});
return elements;
}
|
javascript
|
{
"resource": ""
}
|
q8890
|
_renderDayEvents
|
train
|
function _renderDayEvents(events, doAppend, doRowHeights) {
// where the DOM nodes will eventually end up
var finalContainer = getDaySegmentContainer();
// the container where the initial HTML will be rendered.
// If `doAppend`==true, uses a temporary container.
var renderContainer = doAppend ? $("<div/>") : finalContainer;
var segments = buildSegments(events);
var html;
var elements;
// calculate the desired `left` and `width` properties on each segment object
calculateHorizontals(segments);
// build the HTML string. relies on `left` property
html = buildHTML(segments);
// render the HTML. innerHTML is considerably faster than jQuery's .html()
renderContainer[0].innerHTML = html;
// retrieve the individual elements
elements = renderContainer.children();
// if we were appending, and thus using a temporary container,
// re-attach elements to the real container.
if (doAppend) {
finalContainer.append(elements);
}
// assigns each element to `segment.event`, after filtering them through user callbacks
resolveElements(segments, elements);
// Calculate the left and right padding+margin for each element.
// We need this for setting each element's desired outer width, because of the W3C box model.
// It's important we do this in a separate pass from acually setting the width on the DOM elements
// because alternating reading/writing dimensions causes reflow for every iteration.
segmentElementEach(segments, function(segment, element) {
segment.hsides = hsides(element, true); // include margins = `true`
});
// Set the width of each element
segmentElementEach(segments, function(segment, element) {
element.width(
Math.max(0, segment.outerWidth - segment.hsides)
);
});
// Grab each element's outerHeight (setVerticals uses this).
// To get an accurate reading, it's important to have each element's width explicitly set already.
segmentElementEach(segments, function(segment, element) {
segment.outerHeight = element.outerHeight(true); // include margins = `true`
});
// Set the top coordinate on each element (requires segment.outerHeight)
setVerticals(segments, doRowHeights);
return segments;
}
|
javascript
|
{
"resource": ""
}
|
q8891
|
buildSegments
|
train
|
function buildSegments(events) {
var segments = [];
for (var i=0; i<events.length; i++) {
var eventSegments = buildSegmentsForEvent(events[i]);
segments.push.apply(segments, eventSegments); // append an array to an array
}
return segments;
}
|
javascript
|
{
"resource": ""
}
|
q8892
|
buildSegmentsForEvent
|
train
|
function buildSegmentsForEvent(event) {
var startDate = event.start;
var endDate = exclEndDay(event);
var segments = rangeToSegments(startDate, endDate);
for (var i=0; i<segments.length; i++) {
segments[i].event = event;
}
return segments;
}
|
javascript
|
{
"resource": ""
}
|
q8893
|
calculateHorizontals
|
train
|
function calculateHorizontals(segments) {
var isRTL = opt('isRTL');
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
// Determine functions used for calulating the elements left/right coordinates,
// depending on whether the view is RTL or not.
// NOTE:
// colLeft/colRight returns the coordinate butting up the edge of the cell.
// colContentLeft/colContentRight is indented a little bit from the edge.
var leftFunc = (isRTL ? segment.isEnd : segment.isStart) ? colContentLeft : colLeft;
var rightFunc = (isRTL ? segment.isStart : segment.isEnd) ? colContentRight : colRight;
var left = leftFunc(segment.leftCol);
var right = rightFunc(segment.rightCol);
segment.left = left;
segment.outerWidth = right - left;
}
}
|
javascript
|
{
"resource": ""
}
|
q8894
|
buildHTML
|
train
|
function buildHTML(segments) {
var html = '';
for (var i=0; i<segments.length; i++) {
html += buildHTMLForSegment(segments[i]);
}
return html;
}
|
javascript
|
{
"resource": ""
}
|
q8895
|
setVerticals
|
train
|
function setVerticals(segments, doRowHeights) {
var rowContentHeights = calculateVerticals(segments); // also sets segment.top
var rowContentElements = getRowContentElements(); // returns 1 inner div per row
var rowContentTops = [];
// Set each row's height by setting height of first inner div
if (doRowHeights) {
for (var i=0; i<rowContentElements.length; i++) {
rowContentElements[i].height(rowContentHeights[i]);
}
}
// Get each row's top, relative to the views's origin.
// Important to do this after setting each row's height.
for (var i=0; i<rowContentElements.length; i++) {
rowContentTops.push(
rowContentElements[i].position().top
);
}
// Set each segment element's CSS "top" property.
// Each segment object has a "top" property, which is relative to the row's top, but...
segmentElementEach(segments, function(segment, element) {
element.css(
'top',
rowContentTops[segment.row] + segment.top // ...now, relative to views's origin
);
});
}
|
javascript
|
{
"resource": ""
}
|
q8896
|
buildSegmentRows
|
train
|
function buildSegmentRows(segments) {
var rowCnt = getRowCnt();
var segmentRows = [];
var segmentI;
var segment;
var rowI;
// group segments by row
for (segmentI=0; segmentI<segments.length; segmentI++) {
segment = segments[segmentI];
rowI = segment.row;
if (segment.element) { // was rendered?
if (segmentRows[rowI]) {
// already other segments. append to array
segmentRows[rowI].push(segment);
}
else {
// first segment in row. create new array
segmentRows[rowI] = [ segment ];
}
}
}
// sort each row
for (rowI=0; rowI<rowCnt; rowI++) {
segmentRows[rowI] = sortSegmentRow(
segmentRows[rowI] || [] // guarantee an array, even if no segments
);
}
return segmentRows;
}
|
javascript
|
{
"resource": ""
}
|
q8897
|
sortSegmentRow
|
train
|
function sortSegmentRow(segments) {
var sortedSegments = [];
// build the subrow array
var subrows = buildSegmentSubrows(segments);
// flatten it
for (var i=0; i<subrows.length; i++) {
sortedSegments.push.apply(sortedSegments, subrows[i]); // append an array to an array
}
return sortedSegments;
}
|
javascript
|
{
"resource": ""
}
|
q8898
|
buildSegmentSubrows
|
train
|
function buildSegmentSubrows(segments) {
// Give preference to elements with certain criteria, so they have
// a chance to be closer to the top.
segments.sort(compareDaySegments);
var subrows = [];
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
// loop through subrows, starting with the topmost, until the segment
// doesn't collide with other segments.
for (var j=0; j<subrows.length; j++) {
if (!isDaySegmentCollision(segment, subrows[j])) {
break;
}
}
// `j` now holds the desired subrow index
if (subrows[j]) {
subrows[j].push(segment);
}
else {
subrows[j] = [ segment ];
}
}
return subrows;
}
|
javascript
|
{
"resource": ""
}
|
q8899
|
getRowContentElements
|
train
|
function getRowContentElements() {
var i;
var rowCnt = getRowCnt();
var rowDivs = [];
for (i=0; i<rowCnt; i++) {
rowDivs[i] = allDayRow(i)
.find('div.fc-day-content > div');
}
return rowDivs;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.