_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q36100 | handleError | train | function handleError(promise) {
if (canHandleError) {
return promise.catch(function(err) {
if (ctx) {
ctx.error = err;
if (ctx.emit) ctx.emit('error', ctx);
} else {
ctx = { error: err };
}
return onError(ctx, next).catch(function... | javascript | {
"resource": ""
} |
q36101 | aegean | train | function aegean(path) {
if (path === null || path === undefined || path.constructor !== String) {
throw new Error("aegean expects parameter 1 to be a string");
}
if (fs_1.existsSync(path) === false) {
throw new Error("file \"" + path + "\" does not exist");
}
var stat = fs_1.lstatSyn... | javascript | {
"resource": ""
} |
q36102 | inline | train | function inline(content, path) {
var result = content;
var ast = babylon.parse(content, {
allowImportExportEverywhere: true
});
var statements = ast.program.body;
var gap = 0;
for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) {
var statement = statements... | javascript | {
"resource": ""
} |
q36103 | spawnObservable | train | function spawnObservable(command, args) {
return Observable.create(observer => {
const cmd = spawn(command, args);
observer.next(''); // hack to kick things off, not every command will have a stdout
cmd.stdout.on('data', (data) => { observer.next(data.toString('utf8')); });
cmd.stderr.on('data', (data... | javascript | {
"resource": ""
} |
q36104 | createUmd | train | function createUmd(name, globals) {
// core module is ngd3 the rest are ngd3.feature
const MODULE_NAMES = {
ngd3: 'ngd3',
};
const ENTRIES = {
ngd3: `${process.cwd()}/dist/index.js`,
};
const moduleName = MODULE_NAMES[name];
const entry = ENTRIES[name];
return generateBundle(entry, {
dest: ... | javascript | {
"resource": ""
} |
q36105 | replaceVersionsObservable | train | function replaceVersionsObservable(name, versions) {
return Observable.create((observer) => {
const package = getSrcPackageFile(name);
let pkg = readFileSync(package, 'utf8');
const regexs = Object.keys(versions).map(key =>
({ expr: new RegExp(key, 'g'), key, val: versions[key] }));
regexs.forEa... | javascript | {
"resource": ""
} |
q36106 | getVersions | train | function getVersions() {
const paths = [
getDestPackageFile('ngd3'),
];
return paths
.map(path => require(path))
.map(pkgs => pkgs.version);
} | javascript | {
"resource": ""
} |
q36107 | fixUnicode | train | function fixUnicode(txt) {
txt = txt.replace(/\003/g, ' ');
txt = txt.replace(/\004/g, ' ');
txt = txt.replace(/(\r|\n)/g, ' ');
txt = txt.replace(/[\u007f-\uffff]/g, function (c) {
return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
});
return txt;
} | javascript | {
"resource": ""
} |
q36108 | __fetchTicketInfo | train | function __fetchTicketInfo(server, ticketid, callback) {
assert(server.cache_folder);
var filename = server._ticket_cache_file(ticketid);
//xx console.log("filename " , filename.red);
assert(_.isFunction(callback));
var command = 'issues/' + ticketid.toString() + '.json?include=relations,journal... | javascript | {
"resource": ""
} |
q36109 | RelativePoint | train | function RelativePoint(relativePointDict){
if(!(this instanceof RelativePoint))
return new RelativePoint(relativePointDict)
relativePointDict = relativePointDict || {}
// Check relativePointDict has the required fields
//
// checkType('float', 'relativePointDict.x', relativePointDict.x, {required: true... | javascript | {
"resource": ""
} |
q36110 | initializeStates | train | function initializeStates()
{
// Set all states to NOT_READY
var numVertices = graph.vertexCount();
var vertexIds = graph.getVertexIds();
for(var i = 0; i < numVertices; i++)
{
graph.getVertex(vertexIds[i]).setState("NOT_READY");
}
} | javascript | {
"resource": ""
} |
q36111 | startReadyProcesses | train | function startReadyProcesses()
{
// Start as many processes as we can!
//writeToLog("INFO", "***** maxNumberOfRunningProcesses = " + maxNumberOfRunningProcesses + "; numberOfRunningProcesses = " + numberOfRunningProcesses);
var numVertices = graph.vertexCount();
var vertexIds = graph... | javascript | {
"resource": ""
} |
q36112 | vertexIdsFromArray | train | function vertexIdsFromArray(arr)
{
var numVertices = arr.length;
var vertexIds = [];
for(var i = 0; i < numVertices; i++)
{
vertexIds.push(arr[i].id);
}
return vertexIds;
} | javascript | {
"resource": ""
} |
q36113 | writeToLog | train | function writeToLog(level, msg)
{
var displayPrefix = "PK-" + pkGuid + ": ";
if(loggingMechanism && logUserObject)
{
loggingMechanism.addLog(level, displayPrefix + msg, logUserObject);
}
else
{
console.log(displayPrefix + msg);
}
} | javascript | {
"resource": ""
} |
q36114 | zoomCondition | train | function zoomCondition(zoom) {
var zooms = [];
for (var i = 0; i <= _carto2['default'].tree.Zoom.maxZoom; i++) {
if (zoom & 1 << i) {
zooms.push(i);
}
}
var zoomRanges = detectZoomRanges(zooms),
value,
operator;
if (zoomRanges.length > 1) {
operat... | javascript | {
"resource": ""
} |
q36115 | detectZoomRanges | train | function detectZoomRanges(zooms) {
var ranges = [];
var currentRange = [];
for (var i = 0, z = zooms[0]; i <= zooms.length; i++, z = zooms[i]) {
if (currentRange.length < 2) {
currentRange.push(z);
continue;
}
if (currentRange.length === 2) {
if (z... | javascript | {
"resource": ""
} |
q36116 | onchange | train | function onchange(evt) { // called in context
var ctrl = evt.target;
if (ctrl.parentElement === this.el) {
if (ctrl.value === 'subexp') {
this.children.push(new FilterTree({
parent: this
}));
} else {
this.add({
state: { editor:... | javascript | {
"resource": ""
} |
q36117 | move | train | function move (leftPort, rightPort) {
leftPort = leftPort || 'b'
rightPort = rightPort || 'c'
var write = writeAction('motors_write', [leftPort, rightPort])
/**
* Run motors forever
* @param {Number} speed speed of motor
* @param {Object} opts object of optional params
*/
function * forever (sp... | javascript | {
"resource": ""
} |
q36118 | turnToSpeeds | train | function turnToSpeeds (turn, speed) {
turn = Math.max(Math.min(turn, 100), -100)
var reducedSpeed = otherSpeed(turn, speed)
reducedSpeed = percentToSpeed(reducedSpeed)
speed = percentToSpeed(speed)
return {
left: turn < 0 ? reducedSpeed : speed,
right: turn > 0 ? reducedSpeed : speed
}
} | javascript | {
"resource": ""
} |
q36119 | turnToDegrees | train | function turnToDegrees (turn, speed, degrees) {
turn = Math.max(Math.min(turn, 100), -100)
var opts = turnToSpeeds(turn, speed)
opts.left = { speed: opts.left }
opts.right = { speed: opts.right }
var reducedSpeed = otherSpeed(turn, speed)
var reducedDegrees = Math.round((reducedSpeed / speed) * degrees)
... | javascript | {
"resource": ""
} |
q36120 | joinQueue | train | function joinQueue(fn, ctx, exclusive) {
// Promisify `fn`
fn = promisify(fn, 0);
// Add into queue
var deferred = defer();
this.queue.push({fn: fn, ctx: ctx, deferred: deferred, exclusive: exclusive});
// Run queue
runQueue.call(this);
// Return deferred promise
return deferred.p... | javascript | {
"resource": ""
} |
q36121 | runNext | train | function runNext() {
if (this.locked) return false;
var item = this.queue[0];
if (!item) return false;
if (item.exclusive) {
if (this.running) return false;
this.locked = true;
}
this.queue.shift();
this.running++;
var self = this;
item.fn.call(item.ctx).then(function(res... | javascript | {
"resource": ""
} |
q36122 | runDone | train | function runDone(item, resolved, res) {
// Adjust state of lock
this.running--;
if (this.locked) this.locked = false;
// Resolve/reject promise
item.deferred[resolved ? 'resolve' : 'reject'](res);
// Run queue again
runQueue.call(this);
} | javascript | {
"resource": ""
} |
q36123 | encloseN | train | function encloseN(L, B) {
var circle,
l0 = null,
l1 = L.head,
l2,
p1;
switch (B.length) {
case 1: circle = enclose1(B[0]); break;
case 2: circle = enclose2(B[0], B[1]); break;
case 3: circle = enclose3(B[0], B[1], B[2]); break;
}
while (l1) {
p1 = l1._, l2 = l1.next;
... | javascript | {
"resource": ""
} |
q36124 | kw | train | function kw(bundler) {
assert.equal(typeof bundler, 'object')
const handler = thenify(wreq(bundler))
// Koa middleware.
// @param {Function} next
// @return {Promise}
return function *watchifyRequest(next) {
const ctx = this
return yield handler(this.req, this.res)
.then(success)
.catc... | javascript | {
"resource": ""
} |
q36125 | serialize | train | function serialize(type, source, options) {
var codec = type.codec
if (!codec)
return postEncode(new Buffer([ type.byte ]), options)
var buffer = codec.encode(source, bytewise)
if (options && options.nested && codec.escape)
buffer = codec.escape(buffer)
var hint = typeof codec.length === 'number' ?... | javascript | {
"resource": ""
} |
q36126 | postEncode | train | function postEncode(encoded, options) {
if (options === null)
return encoded
return bytewise.postEncode(encoded, options)
} | javascript | {
"resource": ""
} |
q36127 | cleanUpAndMoveOn | train | function cleanUpAndMoveOn(evt) {
var el = evt.target;
// remove `error` CSS class, which may have been added by `FilterLeaf.prototype.invalid`
el.classList.remove('filter-tree-error');
// set or remove 'warning' CSS class, as per el.value
FilterNode.setWarningClass(el);
if (el === this.view.c... | javascript | {
"resource": ""
} |
q36128 | RegionOfInterest | train | function RegionOfInterest(regionOfInterestDict){
if(!(this instanceof RegionOfInterest))
return new RegionOfInterest(regionOfInterestDict)
regionOfInterestDict = regionOfInterestDict || {}
// Check regionOfInterestDict has the required fields
//
// checkType('RelativePoint', 'regionOfInterestDict.point... | javascript | {
"resource": ""
} |
q36129 | brackets2dots | train | function brackets2dots(string) {
return ({}).toString.call(string) == '[object String]'
? string.replace(REPLACE_BRACKETS, '.$1').replace(LFT_RT_TRIM_DOTS, '')
: ''
} | javascript | {
"resource": ""
} |
q36130 | metriclcs | train | function metriclcs(s1, s2) {
if (typeof s1 !== "string" || typeof s1 !== "string") return NaN;
if (s1 === s2) return 1;
const mlen = Math.max(s1.length, s2.length);
if (mlen === 0) return 1;
return lcsLength(s1, s2) / mlen;
} | javascript | {
"resource": ""
} |
q36131 | plugin | train | function plugin (config) {
/**
* Init
*/
// Throw an error if non-object supplied as `options`
if (config && (typeof(config) !== 'object' || config instanceof Array)) {
throw new Error('metalsmith-nested error: options argument must be an object');
}
config = config || {};
// Set opti... | javascript | {
"resource": ""
} |
q36132 | check | train | function check(files, file, pattern, def) {
let data = files[file];
// Only process utf8 encoded files (so no binary)
if (!utf8(data.contents)) {
return false;
}
// Only process files that match the pattern (if there is a pattern)
if (pattern && !match(file, pattern)[0]) {
... | javascript | {
"resource": ""
} |
q36133 | resolveTemplate | train | function resolveTemplate (tfiles, tfile, resolved, temp = '') {
// If parent layout was called by a page directly (vs. through a child layout)
// inject already resolved content with child `temp`
if (resolved[tfile]) {
return injectContent(resolved[tfile], temp);
}
// Process layout ... | javascript | {
"resource": ""
} |
q36134 | dasherize | train | function dasherize(str) {
return str.replace(
/([a-z])([A-Z])/g,
(_, let1, let2) => `${let1}-${let2.toLowerCase()}`
);
} | javascript | {
"resource": ""
} |
q36135 | write | train | function write (type, port) {
return createAction(WRITE, writeCommand)
/**
* function that returns a write actions
* @private
* @param {string} command
* @param {object} opts move object
* @return {object} write action object
*/
function writeCommand (command, opts) {
return {
... | javascript | {
"resource": ""
} |
q36136 | writeCommand | train | function writeCommand (command, opts) {
return {
type: type,
command: command,
opts: opts,
port: port
}
} | javascript | {
"resource": ""
} |
q36137 | train | function(filepath) {
// Construct the destination file path.
var dest = path.join(
grunt.config('copy.coverage.dest'),
path.relative(process.cwd(), filepath)
);
// Retu... | javascript | {
"resource": ""
} | |
q36138 | getPackageVersion | train | function getPackageVersion() {
var packageJson = path.join(process.cwd(), 'package.json'),
version;
try {
version = require(packageJson).version;
} catch (unused) {
throw new Error('Could not load package.json, please make sure it exists');
}
if (!semver.valid(version)) {
throw new Error('Inva... | javascript | {
"resource": ""
} |
q36139 | writePackageVersion | train | function writePackageVersion(newVersion) {
var packageJson = path.join(process.cwd(), 'package.json'),
raw = require(packageJson);
raw.version = newVersion;
fs.writeFileSync(packageJson, JSON.stringify(raw, null, 2));
} | javascript | {
"resource": ""
} |
q36140 | train | function (obj) {
var ret = {};
if( Object.prototype.toString.call(obj) === '[object Object]' ) {
for (var key in obj) {
ret[key] = arrayClean(obj[key]);
}
}
else if( Object.prototype.toString.call(obj) === '[object Array]' ) {
if (obj.length === 1) {
ret = arrayClean(obj[0]);
}
... | javascript | {
"resource": ""
} | |
q36141 | queryImport | train | function queryImport(styles) {
if (styles.indexOf('@import') < 0) return []
const arr = []
const ast = csstree.parse(styles);
csstree.walk(ast, {
enter: function (node) {
if (node.type === 'Atrule' && node.name === 'import') {
const pat = node.prelude.children.head.da... | javascript | {
"resource": ""
} |
q36142 | handleImportStyle | train | function handleImportStyle(styles, initPath, mayRM) {
if (!!mayRM) {
styles = styles.replace(mayRM, '')
}
if (styles.indexOf('@import') < 0) return styles
const ast = csstree.parse(styles);
csstree.walk(ast, {
enter: function (node) {
if (node.type === 'Atrule') {
... | javascript | {
"resource": ""
} |
q36143 | createStylefromCode | train | function createStylefromCode(styles, abspath) {
//may import other file
const arr = queryImport(styles)
const baseRes = handleImportStyle(styles, abspath)
const obj = {}
const ast = csstree.parse(baseRes);
csstree.walk(ast, {
enter: function (node) {
if (node.type === 'Rule' ... | javascript | {
"resource": ""
} |
q36144 | createStyleDictionary | train | function createStyleDictionary(styles) {
let total = {}
for (let k in styles) {
const val = styles[k]
//sort clz name to judge arbitrary order in multi-className
k = sortSeq(k)
//merge style chain from last condition
const lastEle = getLastEle(k)
//no sharing data... | javascript | {
"resource": ""
} |
q36145 | selectorBlockHandler | train | function selectorBlockHandler(element) {
if (element.type === 'Selector') {
const name = []
let discard = false
element.children.forEach(e => {
switch (e.type) {
case "ClassSelector":
name.push("." + e.name);
break;
... | javascript | {
"resource": ""
} |
q36146 | paddingElementForTransform | train | function paddingElementForTransform(proper, arr) {
//RN not support multi font-family keywords
if (proper === 'font-family') {
return [proper, arr.pop()]
}
//not support such shorthand
if (proper === 'background') {
return ['background-color', arr.join(" ")]
}
//not support s... | javascript | {
"resource": ""
} |
q36147 | styleBlockHandler | train | function styleBlockHandler(element) {
const {property, value} = element
let result = []
const styleContent = value && value.children ? value.children : []
const defaultUnit = "px"
styleContent.forEach(e => {
switch (e.type) {
case "Identifier":
result.push(e.name)... | javascript | {
"resource": ""
} |
q36148 | train | function (uuid) {
uuid = ref.reinterpret(uuid, 16).toString('hex');
return [
uuid.slice(0, 8),
uuid.slice(8, 12),
uuid.slice(12, 16),
uuid.slice(16, 20),
uuid.slice(20, 32)
].join('-');
} | javascript | {
"resource": ""
} | |
q36149 | train | function (trail, options) {
this.trail = trail;
this.options = options || {};
this.cursor = lib.tdb_cursor_new(this.trail.tdb._db);
/*\
|*| Filter logic
\*/
if (typeof this.options.filter != 'undefined') {
const err = lib.tdb_cursor_set_event_filter(this.cursor, this.options.filter);
if (err) {
... | javascript | {
"resource": ""
} | |
q36150 | train | function (options) {
if (!options.path) {
throw new TrailDBError('Path is required');
}
if (!options.fieldNames || !options.fieldNames.length) {
throw new TrailDBError('Field names are required');
}
if (options.path.slice(-4) === '.tdb') {
options.path = options.path.slice(0, -4);
}
this._co... | javascript | {
"resource": ""
} | |
q36151 | train | function (options) {
this._db = lib.tdb_init();
const r = lib.tdb_open(this._db, ref.allocCString(options.path));
if (r !== 0) {
throw new TrailDBError('Could not open TrailDB: ' + r);
}
this.numTrails = lib.tdb_num_trails(this._db);
this.numEvents = lib.tdb_num_events(this._db);
this.numFields = li... | javascript | {
"resource": ""
} | |
q36152 | encodeBound | train | function encodeBound(data, base) {
var prefix = data.prefix
var buffer = prefix ? base.encode(prefix, null) : new Buffer([ data.byte ])
if (data.upper)
buffer = Buffer.concat([ buffer, new Buffer([ 0xff ]) ])
return util.encodedBound(data, buffer)
} | javascript | {
"resource": ""
} |
q36153 | train | function(required, cb) {
var chain = new Chain(config);
chain.on(required, cb);
return chain;
} | javascript | {
"resource": ""
} | |
q36154 | commandFactory | train | function commandFactory(combos, cmd)
{
var command;
// if no combos provided
// consider it as a single command run
if (!cmd)
{
cmd = combos;
combos = [{}];
}
command = partial(iterate, combos, cmd);
command.commandDescription = partial(commandDescription, cmd);
return command;
} | javascript | {
"resource": ""
} |
q36155 | forEachFactory | train | function forEachFactory(properties)
{
// expand object's combinations into an array of objects
if (typeOf(properties) == 'object')
{
properties = cartesian(clone(properties));
}
return {command: partial(commandFactory, properties)};
} | javascript | {
"resource": ""
} |
q36156 | valueFactory | train | function valueFactory(value)
{
function command(cb)
{
cb(null, value);
}
command.commandDescription = partial(commandDescription, 'VALUE SETTER');
return command;
} | javascript | {
"resource": ""
} |
q36157 | commandDescription | train | function commandDescription(desc, state)
{
desc = state[desc] || desc;
return desc.join ? '[' + desc.join(', ') + ']' : desc.toString();
} | javascript | {
"resource": ""
} |
q36158 | iterate | train | function iterate(accumulator, combos, cmd, callback)
{
var params;
// initial call might not have accumulator
if (arguments.length == 3)
{
callback = cmd;
cmd = combos;
combos = accumulator;
accumulator = [];
}
// resolve params from combo reference
if (typeof combos == '... | javascript | {
"resource": ""
} |
q36159 | keepAssigned | train | function keepAssigned(...objs) {
var ka = create(keepAssignedPrototype);
defineProperty(ka, 'objs', { value: [] }); // first-come first-served
[...objs].forEach(o => _keepAssigned(ka, o));
return ka;
} | javascript | {
"resource": ""
} |
q36160 | findFirstProp | train | function findFirstProp(objs, p) {
for (let obj of objs) {
if (obj && obj.hasOwnProperty(p)) { return valueize(obj[p]); }
}
} | javascript | {
"resource": ""
} |
q36161 | calcProp | train | function calcProp(ka, p) {
var val = ka[p];
if (isKeepAssigned(val)) {
recalc(val);
} else {
val.val = findFirstProp(ka.objs, p);
}
} | javascript | {
"resource": ""
} |
q36162 | placeKey | train | function placeKey(ka, v, k, pusher) {
if (isObject(v)) {
if (k in ka) {
_keepAssigned(ka[k], v, pusher);
} else {
ka[k] = subKeepAssigned(ka.objs, k, pusher);
}
} else {
if (k in ka) {
ka[k].val = calcProp(ka, k);
} else {
defineProperty(ka, k, {
get() { return U(... | javascript | {
"resource": ""
} |
q36163 | recalc | train | function recalc(ka) {
for (let [key, val] of objectPairs(ka)) {
if (isKeepAssigned(val)) { recalc(val); }
else { val.val = getter(key); }
}
} | javascript | {
"resource": ""
} |
q36164 | subKeepAssigned | train | function subKeepAssigned(objs, k, pusher) {
var ka = keepAssigned();
objs
.map(propGetter(k))
.filter(Boolean)
.forEach(o => _keepAssigned(ka, o, pusher));
return ka;
} | javascript | {
"resource": ""
} |
q36165 | _keepAssigned | train | function _keepAssigned(ka, o, pusher = unshift) {
// Handle an upwardable object changing, in case of `O(model.obj)`.
function objectChanged(_o) {
replace(ka.objs, o, _o);
recalc(ka);
}
// @TODO: figure out how to handle this.
// upward(o, objectChanged);
function key(v, k) {
placeKey(ka, v,... | javascript | {
"resource": ""
} |
q36166 | train | function(source, dimension) {
// create the matrix
var mat = {}
// if dimension is an integer, the matrix is square
if (_.isFunction(source)
&& _.isInteger(dimension) && dimension >= 0) {
dimension = { x:dimension, y:dimension }
}
// source can be a 2-var predicate function or... | javascript | {
"resource": ""
} | |
q36167 | train | function(sbm) {
// creating matrix
var mat = []
// populate
for (var i = 0; i < sbm.x; i++) {
mat.push([])
for (var j = 0; j < sbm.y; j++) {
mat[i][j] = _.includes(sbm.data[i], j) ? 1 : 0
}
}
// return the matrix
return mat
} | javascript | {
"resource": ""
} | |
q36168 | train | function(n) {
n = _.isInteger(n) ? n : 0
return {
x: n,
y: n,
data: _.map(_.range(n), function (num) {
return [num]
})
}
} | javascript | {
"resource": ""
} | |
q36169 | train | function(matrix) {
// if not square
if (matrix.x != matrix.y) {
return
}
// return trace
return _.filter(matrix.data, function (line, number) {
return _.includes(line, number)
}).length
} | javascript | {
"resource": ""
} | |
q36170 | train | function(sbm) {
// create the matrix
var mat = {}
mat.x = sbm.y
mat.y = sbm.x
mat.data = []
// populate
for (var i = 0; i < mat.x; i++) {
mat.data.push([])
for (var j = 0; j < mat.y; j++) {
if (_.includes(sbm.data[j], i)) {
mat.data[i].push(j)
}
... | javascript | {
"resource": ""
} | |
q36171 | train | function(sbmA, sbmB) {
// check size
if (sbmA.x !== sbmB.x || sbmA.y !== sbmB.y) {
return false
}
// check
return _.every(sbmA.data, function (line, idx) {
return _.isEqual(line.sort(), sbmB.data[idx].sort())
})
} | javascript | {
"resource": ""
} | |
q36172 | train | function(sbm) {
// create the matrix
var mat = {}
mat.x = sbm.x
mat.y = sbm.y
mat.data = []
// populate
for (var i = 0; i < mat.x; i++) {
mat.data[i] = _.difference(_.range(mat.y), sbm.data[i])
}
// return matrix
return mat
} | javascript | {
"resource": ""
} | |
q36173 | train | function(sbmA, sbmB) {
// if not the same sizes
if (sbmA.x != sbmB.x || sbmA.y != sbmB.y) {
return
}
// create the matrix
var mat = {}
mat.x = sbmA.x
mat.y = sbmA.y
mat.data = []
// populate
for (var i = 0; i < mat.x; i++) {
mat.data[i] = _.intersection(sbmA.data[i], ... | javascript | {
"resource": ""
} | |
q36174 | train | function(sbmA, sbmB) {
// if not the same sizes
if (sbmA.x != sbmB.x || sbmA.y != sbmB.y) {
return
}
// create the matrix
var mat = {}
mat.x = sbmA.x
mat.y = sbmA.y
mat.data = []
// populate
for (var i = 0; i < mat.x; i++) {
mat.data[i] = _.union(sbmA.data[i], sbmB.da... | javascript | {
"resource": ""
} | |
q36175 | train | function(sbmA, sbmB) {
// check if size compatible
if (sbmA.y !== sbmB.x) {
return
}
// create a new matrix
return this.make((function (i, j) {
return _.reduce(_.map(_.range(sbmA.y), (function(id) {
return this.check(sbmA, i, id) && this.check(sbmB, id, j)
}).bind(this)), f... | javascript | {
"resource": ""
} | |
q36176 | train | function(sbm, n) {
if (n == 0) {
return this.identity(n)
} else if (n == 1) {
return sbm
} else if (n % 2 == 0) {
return this.pow(this.multiply(sbm, sbm), n/2)
} else {
return this.multiply(sbm, this.pow(this.multiply(sbm, sbm), (n-1)/2))
}
} | javascript | {
"resource": ""
} | |
q36177 | train | function(sbm) {
// if the matrix ain't square, symmetry is off
if (sbm.x !== sbm.y) {
return false
}
// symmetry status
var symmetry = true
// iterate
for (var i = 0; i < sbm.x; i++) {
for (var j = 0; j <= i; j++) {
symmetry = symmetry && ((_.includes(sbm.data[i], j) ^ _... | javascript | {
"resource": ""
} | |
q36178 | train | function(sbm) {
return _.sum(_.map(sbm.data, function (ar) { return ar.length }))
} | javascript | {
"resource": ""
} | |
q36179 | train | function() {
if (!(this instanceof EventParser)) {
return new EventParser();
}
/**
* Parses Mandrill Events request. Sets mandrillEvents property on req. Expects body to contain decoded post body mandrill_events parameter. Please see Madrills article {@link https://mandrill.zendesk.com/hc/en-us/... | javascript | {
"resource": ""
} | |
q36180 | retrieveAssociations | train | function retrieveAssociations(req, res) {
switch(req.accepts(['json', 'html'])) {
// TODO: support HTML in future
//case 'html':
// res.sendFile(path.resolve(__dirname + '/../../web/association.html'));
// break;
default:
var rootUrl = req.protocol + '://' + req.get('host');
var quer... | javascript | {
"resource": ""
} |
q36181 | retrieveAssociation | train | function retrieveAssociation(req, res) {
if(redirect(req.params.id, '', '', res)) {
return;
}
switch(req.accepts(['json', 'html'])) {
// TODO: support HTML in future
//case 'html':
// res.sendFile(path.resolve(__dirname + '/../../web/association.html'));
// break;
default:
var id ... | javascript | {
"resource": ""
} |
q36182 | replaceAssociation | train | function replaceAssociation(req, res) {
if(redirect(req.params.id, '', '', res)) {
return;
}
var id = req.params.id;
var url = req.body.url;
var directory = req.body.directory;
var tags = req.body.tags;
var position = req.body.position;
var rootUrl = req.protocol + '://' + req.get('host');
var qu... | javascript | {
"resource": ""
} |
q36183 | replaceAssociationPosition | train | function replaceAssociationPosition(req, res) {
if(redirect(req.params.id, '../', '/tags', res)) {
return;
}
var id = req.params.id;
var position = req.body.position;
var rootUrl = req.protocol + '://' + req.get('host');
var queryPath = req.originalUrl;
req.chickadee.setAssociation(req, id, null, nul... | javascript | {
"resource": ""
} |
q36184 | deleteAssociationPosition | train | function deleteAssociationPosition(req, res) {
if(redirect(req.params.id, '../', '/tags', res)) {
return;
}
var id = req.params.id;
var rootUrl = req.protocol + '://' + req.get('host');
var queryPath = req.originalUrl;
req.chickadee.removeAssociation(req, id, 'position', rootUrl, queryPath,
... | javascript | {
"resource": ""
} |
q36185 | p_nor | train | function p_nor(z) {
var e, z2, prev = 0.0, t, p, i = 3;
if (z < -12) { return 0.0; }
if (z > 12) { return 1.0; }
if (z === 0.0) { return 0.5; }
if (z > 0) {
e = true;
} else {
e = false;
z = -z;
}
z2 = z * z;
p... | javascript | {
"resource": ""
} |
q36186 | pf | train | function pf(q, n1, n2) {
var eps, fw, s, qe, w1, w2, w3, w4, u, u2, a, b, c, d;
if (q < 0.0 || q > 1.0 || n1 < 1 || n2 < 1) {
console.error('Error : Illegal parameter in pf()!');
return 0.0;
}
if (n1 <= 240 || n2 <= 240) { eps = 1.0e-5; }
if (n2 === 1) {... | javascript | {
"resource": ""
} |
q36187 | puts | train | function puts(error, stdout, stderr) {
if (error || stderr) {
let err = null;
if (error) {
err = `${error}`;
} else if (stderr) {
err = `${stderr}`;
}
returnObj.code = 1;
returnObj.error = err;
}
else if (stdout) {
returnObj.code = 0;
returnObj... | javascript | {
"resource": ""
} |
q36188 | createProxy | train | function createProxy(instance, symbols, enumerable) {
return new Proxy(instance, {
set: (target, propertyName, value) => {
let { symbol, isNew } = getSymbol(symbols, propertyName)
instance[symbol] = value
if (!enumerable && isNew) {
Object.defineProperty(instance, symbol, {
enu... | javascript | {
"resource": ""
} |
q36189 | getSymbol | train | function getSymbol(symbols, propertyName) {
if (symbols.has(propertyName)) {
return {
symbol: symbols.get(propertyName),
isNew: false
}
}
let symbol = Symbol(propertyName)
symbols.set(propertyName, symbol)
return {
symbol,
isNew: true
}
} | javascript | {
"resource": ""
} |
q36190 | parse | train | function parse(size) {
var matches = size.match(regexp);
if (!matches)
return null;
var multiplicator = matches[3] ? +matches[3].replace(/x$/, '') : 1;
return {
width: +matches[1] * multiplicator,
height: +matches[2] * multiplicator
};
} | javascript | {
"resource": ""
} |
q36191 | train | function() {
var streams = this.sourceStreams = toArray(arguments);
if(streams.length > 1) {
this.resultStream = Bacon.mergeAll(streams);
} else {
this.resultStream = streams[0];
}
this.streamsHash = this._computeStreamsHash('any', streams);
// invalidate 'all'
return this;
... | javascript | {
"resource": ""
} | |
q36192 | train | function() {
var streams = this.sourceStreams = toArray(arguments);
if(streams.length === 1) {
this.any.apply(this, streams);
return this;
}
this.resultStream = Bacon.zipAsArray(streams);
this.streamsHash = this._computeStreamsHash('all', streams);
// invalidate 'any'
return ... | javascript | {
"resource": ""
} | |
q36193 | train | function(autocrat, governor, origHandler, context) {
var streamsHash = this.streamsHash,
handlerSequence, isFirstHandler, deferred, handler;
context || (context = this.governor);
if(isFunction(origHandler)) {
origHandler = bind(origHandler, context);
} else if(isString(origHandler)){
... | javascript | {
"resource": ""
} | |
q36194 | train | function(propName, updater) {
var updaterName, handler;
if(!isFunction(updater)) {
updaterName = 'update' + propName[0].toUpperCase() + propName.slice(1);
updater = this.governor[updaterName];
}
if(updater) {
this.then(function(advisorEvent, deferred, consequenceActions, streamEvent)... | javascript | {
"resource": ""
} | |
q36195 | train | function() {
var props = arguments.length ? toArray(arguments) : keys(this.governor.props);
forEach(props, this.updateProp, this);
return this;
} | javascript | {
"resource": ""
} | |
q36196 | removeElements | train | function removeElements(collection, newCollection, index) {
if (index === void 0) { index = 'id'; }
var oldLength = collection.length;
_.remove(collection, function (item) { return !_.some(newCollection, function (c) { return c[index] === item[index]; }); });
return collection.length !==... | javascript | {
"resource": ""
} |
q36197 | sync | train | function sync(collection, newCollection, index) {
if (index === void 0) { index = 'id'; }
var answer = removeElements(collection, newCollection, index);
if (newCollection) {
newCollection.forEach(function (item) {
var oldItem = _.find(collection, function (c) { return... | javascript | {
"resource": ""
} |
q36198 | escapeColons | train | function escapeColons(url) {
var answer = url;
if (_.startsWith(url, 'proxy')) {
answer = url.replace(/:/g, '\\:');
}
else {
answer = url.replace(/:([^\/])/, '\\:$1');
}
return answer;
} | javascript | {
"resource": ""
} |
q36199 | url | train | function url(path) {
if (path) {
if (_.startsWith(path, "/")) {
if (!_urlPrefix) {
// lets discover the base url via the base html element
_urlPrefix = $('base').attr('href') || "";
if (_.endsWith(_urlPrefix, '/')) {
... | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.