_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q52200
|
train
|
function(startPoint, endPoint) {
startPoint = vector.create(startPoint).to3D();
endPoint = vector.create(endPoint).to3D();
if (startPoint === null || endPoint === null) { return null; }
this.line = line.create(startPoint, endPoint.subtract(startPoint));
this.start = startPoint;
this.end = endPoint;
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q52201
|
createCentroids
|
train
|
function createCentroids(k) {
var Centroid = [];
var maxes = this.Observations.maxColumns();
//console.log(maxes);
for(var i = 1; i <= k; i++) {
var centroid = [];
for(var j = 1; j <= this.Observations.cols(); j++) {
centroid.push(Math.random() * maxes.e(j));
}
Centroid.push(centroid);
}
//console.log(centroid)
return $M(Centroid);
}
|
javascript
|
{
"resource": ""
}
|
q52202
|
distanceFrom
|
train
|
function distanceFrom(Centroids) {
var distances = [];
for(var i = 1; i <= this.Observations.rows(); i++) {
var distance = [];
for(var j = 1; j <= Centroids.rows(); j++) {
distance.push(this.Observations.row(i).distanceFrom(Centroids.row(j)));
}
distances.push(distance);
}
return $M(distances);
}
|
javascript
|
{
"resource": ""
}
|
q52203
|
cluster
|
train
|
function cluster(k) {
var Centroids = this.createCentroids(k);
var LastDistances = Matrix$d.Zero(this.Observations.rows(), this.Observations.cols());
var Distances = this.distanceFrom(Centroids);
var Groups;
while(!(LastDistances.eql(Distances))) {
Groups = Distances.minColumnIndexes();
LastDistances = Distances;
var newCentroids = [];
for(var i = 1; i <= Centroids.rows(); i++) {
var centroid = [];
for(var j = 1; j <= Centroids.cols(); j++) {
var sum = 0;
var count = 0;
for(var l = 1; l <= this.Observations.rows(); l++) {
if(Groups.e(l) == i) {
count++;
sum += this.Observations.e(l, j);
}
}
centroid.push(sum / count);
}
newCentroids.push(centroid);
}
Centroids = $M(newCentroids);
Distances = this.distanceFrom(Centroids);
}
return Groups;
}
|
javascript
|
{
"resource": ""
}
|
q52204
|
train
|
function (str) {
var allPairs = [], pairs;
var words = str.split(/\s+/);
for (var i = 0; i < words.length; i++) {
pairs = letterPairs(words[i]);
allPairs.push.apply(allPairs, pairs);
}
return allPairs;
}
|
javascript
|
{
"resource": ""
}
|
|
q52205
|
train
|
function (str1, str2) {
var sanitized_str1 = sanitize(str1);
var sanitized_str2 = sanitize(str2);
var pairs1 = wordLetterPairs(sanitized_str1);
var pairs2 = wordLetterPairs(sanitized_str2);
var intersection = 0, union = pairs1.length + pairs2.length;
if (union === 0) {
if (sanitized_str1 === sanitized_str2) {
return 1;
} else {
return 0;
}
} else {
var i, j, pair1, pair2;
for (i = 0; i < pairs1.length; i++) {
pair1 = pairs1[i];
for (j = 0; j < pairs2.length; j++) {
pair2 = pairs2[j];
if (pair1 == pair2) {
intersection ++;
delete pairs2[j];
break;
}
}
}
return 2 * intersection / union;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52206
|
train
|
function(tokens) {
if(typeof tokens === "string") {
tokens = [tokens];
}
var results = [];
var rule_count = rules$3.length;
var num_tokens = tokens.length;
var i, token, r, rule;
for (i = 0; i < num_tokens; i++) {
token = tokens[i];
// Check the conversion table
if (conversionTable[token.toLowerCase()]) {
results = results.concat(conversionTable[token.toLowerCase()].split(/\W+/));
}
// Apply the rules
else {
var matched = false;
for ( r = 0; r < rule_count; r++) {
rule = rules$3[r];
if (token.match(rule.regex)) {
results = results.concat(token.replace(rule.regex, rule.output).split(/\W+/));
matched = true;
break;
}
}
if (!matched) {
results.push(token);
}
}
}
return results;
}
|
javascript
|
{
"resource": ""
}
|
|
q52207
|
StandardScalerTransforms
|
train
|
function StandardScalerTransforms(vector = [], nan_value = -1, return_nan=false) {
const average = avg(vector);
const standard_dev = sd(vector);
const maximum = max(vector);
const minimum = min(vector);
const scale = (z) => {
const scaledValue = (z - average) / standard_dev;
if (isNaN(scaledValue) && return_nan) return scaledValue;
else if (isNaN(scaledValue) && return_nan === false) return (isNaN(standard_dev)) ? z : standard_dev;
else return scaledValue;
}; // equivalent to MinMaxScaler(z)
const descale = (scaledZ) => {
const descaledValue = (scaledZ * standard_dev) + average;
if (isNaN(descaledValue) && return_nan) return descaledValue;
else if (isNaN(descaledValue) && return_nan === false) return (isNaN(standard_dev)) ? scaledZ : standard_dev;
else return descaledValue;
};
const values = vector.map(scale)
.map(val => {
if (isNaN(val)) return nan_value;
else return val;
});
return {
components: {
average,
standard_dev,
maximum,
minimum,
},
scale,
descale,
values,
};
}
|
javascript
|
{
"resource": ""
}
|
q52208
|
assocationRuleLearning
|
train
|
function assocationRuleLearning(transactions =[], options) {
return new Promise((resolve, reject) => {
try {
const config = Object.assign({}, {
support: 0.4,
minLength: 2,
summary: true,
valuesMap: new Map(),
}, options);
const fpgrowth = new FPGrowth(config.support);
fpgrowth.exec(transactions)
.then(results => {
const itemsets = (results.itemsets) ? results.itemsets : results;
// console.log('itemsets', itemsets)
if (config.summary) {
resolve(itemsets
.map(itemset => ({
items_labels: itemset.items.map(item => config.valuesMap.get(item)),
items: itemset.items,
support: itemset.support,
support_percent: itemset.support / transactions.length,
}))
.filter(itemset => itemset.items.length > 1)
.sort((a, b) => b.support - a.support));
} else {
resolve(results);
}
})
.catch(reject);
} catch (e) {
reject(e);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q52209
|
cross_validate_score
|
train
|
function cross_validate_score(options = {}) {
const config = Object.assign({}, {
// classifier,
// regression,
// dataset,
// testingset,
dependentFeatures: [['X', ], ],
independentFeatures: [['Y', ], ],
// random_state,
folds: 10,
accuracy: 'standardError',
use_train_x_matrix: true,
use_train_y_matrix: false,
use_train_y_vector: false,
use_estimates_y_vector: false,
}, options);
const classifier = config.classifier;
const regression = config.regression;
const folds = cross_validation_split(config.dataset, {
folds: config.folds,
random_state: config.random_state,
});
const testingDataSet = new DataSet(config.testingset);
const y_test_matrix = testingDataSet.columnMatrix(config.independentFeatures);
const x_test_matrix = testingDataSet.columnMatrix(config.dependentFeatures);
const actuals = util.pivotVector(y_test_matrix)[ 0 ];
// console.log({ actuals });
const prediction_accuracies = folds.map(fold => {
const trainingDataSet = new DataSet(fold);
const x_train = trainingDataSet.columnMatrix(config.dependentFeatures);
const y_train = trainingDataSet.columnMatrix(config.independentFeatures);
const x_train_matrix = (config.use_train_x_matrix)
? new Matrix(x_train)
: x_train;
const y_train_matrix = (config.use_train_y_matrix)
? new Matrix(y_train)
: (config.use_train_y_vector)
? util.pivotVector(y_train)[0]
: y_train;
if (regression) {
let regressor;
let pred_y_test;
if (typeof regression.train === 'function') {
regressor = regression.train(x_train_matrix, y_train_matrix, config.modelOptions);
pred_y_test = regression.predict(x_test_matrix);
} else {
regressor = new regression(x_train_matrix, y_train_matrix, config.modelOptions);
pred_y_test = regressor.predict(x_test_matrix);
}
// console.log({ x_test_matrix });
// console.log({ pred_y_test });
const estimates = pred_y_test;//util.pivotVector(pred_y_test)[0];
// console.log({ estimates, actuals });
return (config.accuracy === 'standardError')
? util.standardError(actuals, estimates)
: util.rSquared(actuals, estimates);
} else {
let classification;
let estimates;
if (typeof classifier.train === 'function') {
classifier.train(x_train_matrix, y_train_matrix, config.modelOptions);
estimates = classifier.predict(x_test_matrix);
} else {
classification = new classifier(x_train_matrix, y_train_matrix, config.modelOptions);
estimates = classification.predict(x_test_matrix);
}
// classification.train(x_train_matrix, y_train_matrix);
// classifier.train(x_train_matrix, y_train_matrix);
const compareEstimates = (config.use_estimates_y_vector)
? util.pivotVector(estimates)[ 0 ]
: estimates;
const CM = ConfusionMatrix.fromLabels(actuals, compareEstimates);
return CM.getAccuracy();
}
});
return prediction_accuracies;
}
|
javascript
|
{
"resource": ""
}
|
q52210
|
grid_search
|
train
|
function grid_search(options = {}) {
const config = Object.assign({}, {
return_parameters: false,
compare_score:'mean',
sortAccuracyScore:'desc',
parameters: {},
}, options);
const regressor = config.regression;
const classification = config.classifier;
const sortAccuracyScore = (!options.sortAccuracyScore && config.regression)
? 'asc'
: config.sortAccuracyScore;
// const scoreSorter = ;
const gs = new GridSearch({
params: config.parameters,
run_callback: (params) => {
if (config.regression) {
config.regression = new regressor(params);
} else {
config.classifier = new classification(params);
}
const score = cross_validate_score(config);
return (config.compare_score)
? util[config.compare_score](score)
: score;
},
});
gs.run();
const accuracySorter = (sortAccuracyScore === 'desc')
? (a, b) => b.results - a.results
: (a, b) => a.results - b.results;
const results = gs._results.sort(accuracySorter);
// GridSearch;
return config.return_parameters
? results
: results[ 0 ];
}
|
javascript
|
{
"resource": ""
}
|
q52211
|
epipeError
|
train
|
function epipeError(err) {
if (err.code === 'EPIPE' || err.errno === 32) return process.exit;
if (process.stdout.listeners('error').length <= 1) {
process.stdout.removeAllListeners();
process.stdout.emit('error', err);
process.stdout.on('error', epipeError);
}
}
|
javascript
|
{
"resource": ""
}
|
q52212
|
train
|
function (source, target, isExternal) {
// Clone source
var pkg = JSON.parse(JSON.stringify(source));
// Validation of source package.
["name", "description"].forEach(function (name) {
if (!pkg[name]) {
throw new Error("Source object missing field: " + name);
}
});
var nameRe = new RegExp("(^|.*\/)(" + source.name + ")(\/.*|$)");
// Update with internal "development" names
pkg.name += "-dev";
pkg.description += " (Development)";
// Update external fields to add `-dev` if applicable and present.
if (isExternal) {
[
"repository.url",
"bugs.url",
"homepage"
].forEach(function (paths) {
// Traverse the package structure.
var parts = paths.split(".");
var pkgPart = pkg;
parts.forEach(function (part, i) {
if (pkgPart && pkgPart[part]) {
if (i + 1 === parts.length) {
// Done! Update part if present.
if (nameRe.test(pkgPart[part])) {
pkgPart[part] = pkgPart[part].replace(nameRe, "$1" + pkg.name + "$3");
}
return;
}
// Increment
pkgPart = pkgPart[part];
return;
}
// Failed.
pkgPart = null;
});
});
}
// Copy back in dependencies from dev package
pkg.dependencies = (target || {}).dependencies || {};
pkg.peerDependencies = (target || {}).peerDependencies || {};
// Remove scripts, dev deps, etc.
pkg.scripts = {};
pkg.devDependencies = {};
return pkg;
}
|
javascript
|
{
"resource": ""
}
|
|
q52213
|
train
|
function (value) {
var o = this.options, min = o.min, max = o.max;
this.bar.children().attr({ "aria-valuenow": value });
if (o.sliderType == "range") {
var handles = this._handles();
handles.eq(0).attr({ "aria-valuemin": min });
handles.eq(1).attr({ "aria-valuemax": max });
if (this._active == 1) handles.eq(1).attr({ "aria-valuemin": value });
else handles.eq(0).attr({ "aria-valuemax": value });
}
else this.bar.children().attr({ "aria-valuemin": min, "aria-valuemax": max });
}
|
javascript
|
{
"resource": ""
}
|
|
q52214
|
train
|
function () {
var _data = this._dataElement().data("bind");
if (typeof _data == "string" && typeof ko == "object") {
var _vm = ko.dataFor(this._dataElement()[0]);
if (typeof _vm == "undefined") return true;
var _all = _data.split(","), _handler;
for (var i = 0; i < _all.length; i++) {
var d = _all[i].split(":");
if ($.trim(d[0]) == "value") {
_handler = $.trim(d[1]);
break;
}
}
if (_handler) {
this._isKO = true;
ko.computed(function () { this.option("value", _vm[_handler]()); }, this);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52215
|
train
|
function () {
if (typeof angular == "object" && typeof angular.element == "function") {
this._ngName = this._dataElement().attr("ng-model");
if (typeof this._ngName == "string") {
this._isAngular = true; var that = this;
this._scope().$watch(this._ngName, function (newValue, oldValue) { that.option("value", newValue); });
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52216
|
CreateRoundSlider
|
train
|
function CreateRoundSlider(options, args) {
for (var i = 0; i < this.length; i++) {
var that = this[i], instance = $.data(that, pluginName);
if (!instance) {
var _this = new RoundSlider(that, options);
_this._saveInstanceOnElement();
_this._saveInstanceOnID();
if (_this._raise("beforeCreate") !== false) {
_this._init();
_this._raise("create");
}
else _this._removeData();
}
else if ($.isPlainObject(options)) {
if (typeof instance.option === "function") instance.option(options);
else if (that.id && window[that.id] && typeof window[that.id].option === "function") {
window[that.id].option(options);
}
}
else if (typeof options === "string") {
if (typeof instance[options] === "function") {
if ((options === "option" || options.indexOf("get") === 0) && args[2] === undefined) {
return instance[options](args[1]);
}
instance[options](args[1], args[2]);
}
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q52217
|
filter
|
train
|
function filter(rows = [], filters = [], filterText, columns) {
let filteredRows = rows.slice(0);
if (filters.length === 0 && !filterText) {
return filteredRows;
}
const textFilters = [
...(filterText ? [filterText.toLowerCase()] : []),
...filters.filter(f => f.textFilter).map(f => f.value),
];
const valueFilters = filters.filter(f => f.valueFilter);
// apply text filters across all columns
if (textFilters.length > 0) {
filteredRows = _.filter(rows, row => _.some(columns, (column) => {
if (!column.searchable) {
return false;
}
const normalized = String(_.get(row, column.key)).toLowerCase();
return _.every(textFilters, f => normalized.indexOf(f) > -1);
}));
}
// apply value filters on filterable columns
if (valueFilters.length > 0) {
const groups = _.groupBy(valueFilters, 'key');
filteredRows = _.filter(filteredRows, row => _.every(
groups,
(groupFilters, groupKey) => {
const value = _.get(row, groupKey);
return _.some(groupFilters, f => f.value === value);
}
));
}
return filteredRows;
}
|
javascript
|
{
"resource": ""
}
|
q52218
|
train
|
function (el) {
if (isMSIE8) {
// Fallback for MSIE8, will most probably fail on edge cases
return [ 0, 0, el.offsetWidth, el.offsetHeight];
}
var styles = window.getComputedStyle(el);
// getComputedStyle() should return values already in pixels, so using parseInt()
// is not as much as a hack as it seems to be.
return [
parseInt(styles.marginLeft),
parseInt(styles.marginTop),
parseInt(styles.marginLeft) + parseInt(styles.width),
parseInt(styles.marginTop) + parseInt(styles.height)
];
}
|
javascript
|
{
"resource": ""
}
|
|
q52219
|
loadUid
|
train
|
function loadUid (cb) {
// if we're not in unsafe-perm mode, then figure out who
// to run stuff as. Do this first, to support `npm update npm -g`
if (!this.get("unsafe-perm")) {
getUid(this.get("user"), this.get("group"), cb)
} else {
process.nextTick(cb)
}
}
|
javascript
|
{
"resource": ""
}
|
q52220
|
computeExpires
|
train
|
function computeExpires(str) {
const lastCh = str.charAt(str.length - 1);
const value = parseInt(str, 10);
let expires = new Date();
switch (lastCh) {
case 'Y': expires.setFullYear(expires.getFullYear() + value); break;
case 'M': expires.setMonth(expires.getMonth() + value); break;
case 'D': expires.setDate(expires.getDate() + value); break;
case 'h': expires.setHours(expires.getHours() + value); break;
case 'm': expires.setMinutes(expires.getMinutes() + value); break;
case 's': expires.setSeconds(expires.getSeconds() + value); break;
default: expires = new Date(str);
}
return expires;
}
|
javascript
|
{
"resource": ""
}
|
q52221
|
convert
|
train
|
function convert(opts) {
let res = '';
// eslint-disable-next-line
for (const key in opts) {
if (hasOwn(opts, key)) {
if (/^expires$/i.test(key)) {
let expires = opts[key];
if (typeof expires !== 'object') {
expires += typeof expires === 'number' ? 'D' : '';
expires = computeExpires(expires);
}
res += `;${key}=${expires.toUTCString()}`;
} else if (/^secure$/.test(key)) {
if (opts[key]) {
res += `;${key}`;
}
} else {
res += `;${key}=${opts[key]}`;
}
}
}
if (!hasOwn(opts, 'path')) {
res += ';path=/';
}
return res;
}
|
javascript
|
{
"resource": ""
}
|
q52222
|
isEnabled
|
train
|
function isEnabled() {
const key = '@key@';
const value = '1';
const re = new RegExp(`(?:^|; )${key}=${value}(?:;|$)`);
document.cookie = `${key}=${value}`;
const enabled = re.test(document.cookie);
if (enabled) {
// eslint-disable-next-line
remove(key);
}
return enabled;
}
|
javascript
|
{
"resource": ""
}
|
q52223
|
get
|
train
|
function get(key, decoder = decodeURIComponent) {
if ((typeof key !== 'string') || !key) {
return null;
}
const reKey = new RegExp(`(?:^|; )${escapeRe(key)}(?:=([^;]*))?(?:;|$)`);
const match = reKey.exec(document.cookie);
if (match === null) {
return null;
}
return typeof decoder === 'function' ? decoder(match[1]) : match[1];
}
|
javascript
|
{
"resource": ""
}
|
q52224
|
getAll
|
train
|
function getAll(decoder = decodeURIComponent) {
const reKey = /(?:^|; )([^=]+?)(?:=([^;]*))?(?:;|$)/g;
const cookies = {};
let match;
/* eslint-disable no-cond-assign */
while ((match = reKey.exec(document.cookie))) {
reKey.lastIndex = (match.index + match.length) - 1;
cookies[match[1]] = typeof decoder === 'function' ? decoder(match[2]) : match[2];
}
return cookies;
}
|
javascript
|
{
"resource": ""
}
|
q52225
|
remove
|
train
|
function remove(key, options) {
let opts = { expires: -1 };
if (options) {
opts = { ...options, ...opts };
}
return set(key, 'a', opts);
}
|
javascript
|
{
"resource": ""
}
|
q52226
|
train
|
function(subject) {
if (this.isScalar() && this.hasSearch()) {
var search = this.getSearch();
return this.highlightChildren(subject, search);
}
return this.props.children;
}
|
javascript
|
{
"resource": ""
}
|
|
q52227
|
train
|
function() {
if (this.props.search instanceof RegExp) {
return this.props.search;
}
var flags = '';
if (!this.props.caseSensitive) {
flags +='i';
}
var search = this.props.search;
if (typeof this.props.search === 'string') {
search = escapeStringRegexp(search);
}
if (this.props.ignoreDiacritics) {
search = removeDiacritics(search, this.props.diacriticsBlacklist);
}
return new RegExp(search, flags);
}
|
javascript
|
{
"resource": ""
}
|
|
q52228
|
train
|
function(subject, search) {
var matches = search.exec(subject);
if (matches) {
return {
first: matches.index,
last: matches.index + matches[0].length
};
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52229
|
train
|
function(subject, search) {
var children = [];
var remaining = subject;
while (remaining) {
var remainingCleaned = (this.props.ignoreDiacritics
? removeDiacritics(remaining, this.props.diacriticsBlacklist)
: remaining
);
if (!search.test(remainingCleaned)) {
children.push(this.renderPlain(remaining));
return children;
}
var boundaries = this.getMatchBoundaries(remainingCleaned, search);
if (boundaries.first === 0 && boundaries.last === 0) {
// Regex zero-width match
return children;
}
// Capture the string that leads up to a match...
var nonMatch = remaining.slice(0, boundaries.first);
if (nonMatch) {
children.push(this.renderPlain(nonMatch));
}
// Now, capture the matching string...
var match = remaining.slice(boundaries.first, boundaries.last);
if (match) {
children.push(this.renderHighlight(match));
}
// And if there's anything left over, recursively run this method again.
remaining = remaining.slice(boundaries.last);
}
return children;
}
|
javascript
|
{
"resource": ""
}
|
|
q52230
|
train
|
function(string) {
this.count++;
return React.createElement(this.props.matchElement, {
key: this.count,
className: this.props.matchClass,
style: this.props.matchStyle,
children: string
});
}
|
javascript
|
{
"resource": ""
}
|
|
q52231
|
train
|
function(node, e){
if (node){
var currMousePos = e.position || e.cyPosition;
var topLeft = {
x: (node.position("x") - node.width() / 2 - parseFloat(node.css('padding-left'))),
y: (node.position("y") - node.height() / 2 - parseFloat(node.css('padding-top')))};
var bottomRight = {
x: (node.position("x") + node.width() / 2 + parseFloat(node.css('padding-right'))),
y: (node.position("y") + node.height() / 2+ parseFloat(node.css('padding-bottom')))};
if (currMousePos.x >= topLeft.x && currMousePos.y >= topLeft.y &&
currMousePos.x <= bottomRight.x && currMousePos.y <= bottomRight.y){
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q52232
|
evalOptions
|
train
|
function evalOptions(options) {
var animate = typeof options.animate === 'function' ? options.animate.call() : options.animate;
var fisheye = typeof options.fisheye === 'function' ? options.fisheye.call() : options.fisheye;
options.animate = animate;
options.fisheye = fisheye;
}
|
javascript
|
{
"resource": ""
}
|
q52233
|
train
|
function (nodes, options) {
// If there is just one node to expand we need to animate for fisheye view, but if there are more then one node we do not
if (nodes.length === 1) {
var node = nodes[0];
if (node._private.data.collapsedChildren != null) {
// Expand the given node the third parameter indicates that the node is simple which ensures that fisheye parameter will be considered
this.expandNode(node, options.fisheye, true, options.animate, options.layoutBy);
}
}
else {
// First expand given nodes and then perform layout according to the layoutBy parameter
this.simpleExpandGivenNodes(nodes, options.fisheye);
this.endOperation(options.layoutBy);
}
/*
* return the nodes to undo the operation
*/
return nodes;
}
|
javascript
|
{
"resource": ""
}
|
|
q52234
|
train
|
function (nodes, options) {
/*
* In collapse operation there is no fisheye view to be applied so there is no animation to be destroyed here. We can do this
* in a batch.
*/
cy.startBatch();
this.simpleCollapseGivenNodes(nodes, options);
cy.endBatch();
nodes.trigger("position"); // position not triggered by default when collapseNode is called
this.endOperation(options.layoutBy);
// Update the style
cy.style().update();
/*
* return the nodes to undo the operation
*/
return nodes;
}
|
javascript
|
{
"resource": ""
}
|
|
q52235
|
train
|
function (root) {
var children = root.children();
for (var i = 0; i < children.length; i++) {
var node = children[i];
this.collapseBottomUp(node);
}
//If the root is a compound node to be collapsed then collapse it
if (root.data("collapse") && root.children().length > 0) {
this.collapseNode(root);
root.removeData("collapse");
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52236
|
train
|
function (root, applyFishEyeViewToEachNode) {
if (root.data("expand") && root._private.data.collapsedChildren != null) {
// Expand the root and unmark its expand data to specify that it is no more to be expanded
this.expandNode(root, applyFishEyeViewToEachNode);
root.removeData("expand");
}
// Make a recursive call for children of root
var children = root.children();
for (var i = 0; i < children.length; i++) {
var node = children[i];
this.expandTopDown(node);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52237
|
train
|
function (renderedPosition) {
var pan = cy.pan();
var zoom = cy.zoom();
var x = (renderedPosition.x - pan.x) / zoom;
var y = (renderedPosition.y - pan.y) / zoom;
return {
x: x,
y: y
};
}
|
javascript
|
{
"resource": ""
}
|
|
q52238
|
train
|
function (node) {
if (node._private.data.collapsedChildren == null) {
node.data('position-before-collapse', {
x: node.position().x,
y: node.position().y
});
node.data('size-before-collapse', {
w: node.outerWidth(),
h: node.outerHeight()
});
var children = node.children();
children.unselect();
children.connectedEdges().unselect();
node.trigger("expandcollapse.beforecollapse");
this.barrowEdgesOfcollapsedChildren(node);
this.removeChildren(node, node);
node.addClass('cy-expand-collapse-collapsed-node');
node.trigger("expandcollapse.aftercollapse");
node.position(node.data('position-before-collapse'));
//return the node to undo the operation
return node;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52239
|
train
|
function(node, collapsedChildren){
var children = node.data('collapsedChildren');
var i;
for (i=0; i < children.length; i++){
if (children[i].data('collapsedChildren')){
collapsedChildren = collapsedChildren.union(this.getCollapsedChildrenRecursively(children[i], collapsedChildren));
}
collapsedChildren = collapsedChildren.union(children[i]);
}
return collapsedChildren;
}
|
javascript
|
{
"resource": ""
}
|
|
q52240
|
train
|
function(moduleName, moduleClosure) {
var wm = this; // GLOBAL.WebModule
// https://github.com/uupaa/WebModule/wiki/SwitchModulePattern
var alias = wm[moduleName] ? (moduleName + "_") : moduleName;
if (!wm[alias]) { // secondary module already exported -> skip
wm[alias] = moduleClosure(GLOBAL); // evaluate the module entity
wm.closure[alias] = moduleClosure + ""; // stock
if (wm.publish && !GLOBAL[alias]) {
GLOBAL[alias] = wm[alias]; // publish to global
}
}
return wm[alias];
}
|
javascript
|
{
"resource": ""
}
|
|
q52241
|
train
|
function(moduleName, // @arg ModuleNameString
moduleClosure) { // @arg JavaScriptCodeString
// @ret ModuleObject
var wm = this; // GLOBAL.WebModule
// https://github.com/uupaa/WebModule/wiki/SwitchModulePattern
var alias = wm[moduleName] ? (moduleName + "_") : moduleName;
if (!wm[alias]) { // secondary module already exported -> skip
wm[alias] = moduleClosure(GLOBAL, wm, wm.VERIFY, wm.VERBOSE); // evaluate the module entity.
wm.CODE[alias] = moduleClosure + ""; // store to the container.
if (wm.PUBLISH && !GLOBAL[alias]) {
GLOBAL[alias] = wm[alias]; // module publish to global namespace.
}
}
return wm[alias];
}
|
javascript
|
{
"resource": ""
}
|
|
q52242
|
buffer2ArrayBuffer
|
train
|
function buffer2ArrayBuffer(buffer) {
var buf = new ArrayBuffer(buffer.length);
var bufView = new Uint8Array(buf);
for (var i = 0; i < buffer.length; i++) {
bufView[i] = buffer[i];
}
return buf;
}
|
javascript
|
{
"resource": ""
}
|
q52243
|
batchLoaderFunc
|
train
|
function batchLoaderFunc(graphqlType, serializeRecordKey, getRecords) {
return keys => getRecords(keys)
.then(resultArray => getResultsByKey(
keys, extractAllItems(resultArray), serializeRecordKey, graphqlType,
{ onError: logger }
)
);
}
|
javascript
|
{
"resource": ""
}
|
q52244
|
extend
|
train
|
function extend(target, source, modify) {
var result = target ? modify ? target : extend({}, target, true) : {};
if (!source) return result;
for (var key in source) {
if (source.hasOwnProperty(key) && source[key] !== undefined) {
result[key] = source[key];
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q52245
|
extractAllItems
|
train
|
function extractAllItems (result) {
if (!result) return null;
if (!Array.isArray(result)) result = ('data' in result) ? result.data : result;
if (!result) return null;
if (!Array.isArray(result)) result = [result];
return result;
}
|
javascript
|
{
"resource": ""
}
|
q52246
|
extractFirstItem
|
train
|
function extractFirstItem (result) {
const data = extractAllItems(result);
if (!data) return null;
if (data.length > 1) throw new Error(`service.find expected 0 or 1 objects, not ${data.length}. (extractFirstItem)`);
return data.length ? data[0] : null;
}
|
javascript
|
{
"resource": ""
}
|
q52247
|
checkDisplay
|
train
|
function checkDisplay () {
var myPermissions = self.allProperties[resizeListenerId] // JSON.parse(el.dataset.responsives)
var curWidth = window.innerWidth
var initial = el.dataset.initialDisplay ? el.dataset.initialDisplay : ''
var parameters = self._rPermissions[binding.arg]
for (let i in parameters) {
if (curWidth >= parameters[i].min && curWidth <= parameters[i].max) {
if (myPermissions.lastBp !== i) {
if (self.allProperties[resizeListenerId].useClass) {
el.classList.add(myPermissions.bpSet + '-' + i)
el.classList.remove(myPermissions.bpSet + '-' + myPermissions.lastBp)
} else {
el.style.display = myPermissions[i] ? initial : 'none'
}
self.allProperties[resizeListenerId].lastBp = i
}
break
}
}
}
|
javascript
|
{
"resource": ""
}
|
q52248
|
train
|
function (el, binding, vnode) {
let resizeListenerId = el.dataset.responsives
delete self.resizeListeners[resizeListenerId]
}
|
javascript
|
{
"resource": ""
}
|
|
q52249
|
htmlDecode
|
train
|
function htmlDecode(input) {
if (input === " ") return input;
const doc = new DOMParser().parseFromString(input.replace(/<[^>]+>/g, ""), "text/html");
return doc.documentElement.textContent;
}
|
javascript
|
{
"resource": ""
}
|
q52250
|
train
|
function() {
this.id = 'jq-signature-canvas-' + (++idCounter);
// Set up the canvas
this.$canvas = $(canvasFixture).appendTo(this.$element);
this.$canvas.attr({
width: this.settings.width,
height: this.settings.height
});
this.$canvas.css({
boxSizing: 'border-box',
width: this.settings.width + 'px',
height: this.settings.height + 'px',
border: this.settings.border,
background: this.settings.background,
cursor: 'crosshair'
});
this.$canvas.attr('id', this.id);
// Fit canvas to width of parent
if (this.settings.autoFit === true) {
this._resizeCanvas();
// TODO - allow for dynamic canvas resizing
// (need to save canvas state before changing width to avoid getting cleared)
// var timeout = false;
// $(window).on('resize', $.proxy(function(e) {
// clearTimeout(timeout);
// timeout = setTimeout($.proxy(this._resizeCanvas, this), 250);
// }, this));
}
this.canvas = this.$canvas[0];
this._resetCanvas();
// Listen for pointer/mouse/touch events
// TODO - PointerEvent isn't fully supported, but eventually do something like this:
// if (window.PointerEvent) {
// this.$canvas.parent().css('-ms-touch-action', 'none');
// this.$canvas.on("pointerdown MSPointerDown", $.proxy(this._downHandler, this));
// this.$canvas.on("pointermove MSPointerMove", $.proxy(this._moveHandler, this));
// this.$canvas.on("pointerup MSPointerUp", $.proxy(this._upHandler, this));
// }
// else {
// this.$canvas.on('mousedown touchstart', $.proxy(this._downHandler, this));
// this.$canvas.on('mousemove touchmove', $.proxy(this._moveHandler, this));
// this.$canvas.on('mouseup touchend', $.proxy(this._upHandler, this));
// }
this.$canvas.on('mousedown touchstart', $.proxy(this._downHandler, this));
this.$canvas.on('mousemove touchmove', $.proxy(this._moveHandler, this));
this.$canvas.on('mouseup touchend', $.proxy(this._upHandler, this));
// Start drawing
var that = this;
(function drawLoop() {
window.requestAnimFrame(drawLoop);
that._renderCanvas();
})();
}
|
javascript
|
{
"resource": ""
}
|
|
q52251
|
train
|
function (e) {
this.drawing = true;
this.lastPos = this.currentPos = this._getPosition(e);
// Prevent scrolling, etc
$('body').css('overflow', 'hidden');
e.preventDefault();
}
|
javascript
|
{
"resource": ""
}
|
|
q52252
|
train
|
function (e) {
this.drawing = false;
// Trigger a change event
var changedEvent = $.Event('jq.signature.changed');
this.$element.trigger(changedEvent);
// Allow scrolling again
$('body').css('overflow', 'auto');
e.preventDefault();
}
|
javascript
|
{
"resource": ""
}
|
|
q52253
|
train
|
function() {
if (this.drawing) {
this.ctx.beginPath();
this.ctx.moveTo(this.lastPos.x, this.lastPos.y);
this.ctx.lineTo(this.currentPos.x, this.currentPos.y);
this.ctx.stroke();
this.lastPos = this.currentPos;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52254
|
train
|
function() {
this.ctx = this.canvas.getContext("2d");
this.ctx.strokeStyle = this.settings.lineColor;
this.ctx.lineWidth = this.settings.lineWidth;
}
|
javascript
|
{
"resource": ""
}
|
|
q52255
|
read
|
train
|
function read (path, options) {
return parse(fs.createReadStream(path, options), Object.assign({}, options, { ndjson: false }))
}
|
javascript
|
{
"resource": ""
}
|
q52256
|
write
|
train
|
function write (path, data, options) {
const Promise = promise(options)
return new Promise((resolve, reject) => {
streamify(data, options)
.pipe(fs.createWriteStream(path, options))
.on('finish', () => {
resolve()
})
.on('error', reject)
.on('dataError', reject)
})
}
|
javascript
|
{
"resource": ""
}
|
q52257
|
stringify
|
train
|
function stringify (data, options) {
const json = []
const Promise = promise(options)
const stream = streamify(data, options)
let resolve, reject
stream.on('data', read)
stream.on('end', end)
stream.on('error', error)
stream.on('dataError', error)
return new Promise((res, rej) => {
resolve = res
reject = rej
})
function read (chunk) {
json.push(chunk)
}
function end () {
resolve(json.join(''))
}
function error (e) {
reject(e)
}
}
|
javascript
|
{
"resource": ""
}
|
q52258
|
unpipe
|
train
|
function unpipe (callback, options) {
check.assert.function(callback, 'Invalid callback argument')
const jsonstream = new stream.PassThrough()
parse(jsonstream, Object.assign({}, options, { ndjson: false }))
.then(data => callback(null, data))
.catch(error => callback(error))
return jsonstream
}
|
javascript
|
{
"resource": ""
}
|
q52259
|
loadImplementation
|
train
|
function loadImplementation(implementation){
var impl = null
if(shouldPreferGlobalPromise(implementation)){
// if no implementation or env specified use global.Promise
impl = {
Promise: global.Promise,
implementation: 'global.Promise'
}
} else if(implementation){
// if implementation specified, require it
var lib = require(implementation)
impl = {
Promise: lib.Promise || lib,
implementation: implementation
}
} else {
// try to auto detect implementation. This is non-deterministic
// and should prefer other branches, but this is our last chance
// to load something without throwing error
impl = tryAutoDetect()
}
if(impl === null){
throw new Error('Cannot find any-promise implementation nor'+
' global.Promise. You must install polyfill or call'+
' require("any-promise/register") with your preferred'+
' implementation, e.g. require("any-promise/register/bluebird")'+
' on application load prior to any require("any-promise").')
}
return impl
}
|
javascript
|
{
"resource": ""
}
|
q52260
|
shouldPreferGlobalPromise
|
train
|
function shouldPreferGlobalPromise(implementation){
if(implementation){
return implementation === 'global.Promise'
} else if(typeof global.Promise !== 'undefined'){
// Load global promise if implementation not specified
// Versions < 0.11 did not have global Promise
// Do not use for version < 0.12 as version 0.11 contained buggy versions
var version = (/v(\d+)\.(\d+)\.(\d+)/).exec(process.version)
return !(version && +version[1] == 0 && +version[2] < 12)
}
// do not have global.Promise or another implementation was specified
return false
}
|
javascript
|
{
"resource": ""
}
|
q52261
|
tryAutoDetect
|
train
|
function tryAutoDetect(){
var libs = [
"es6-promise",
"promise",
"native-promise-only",
"bluebird",
"rsvp",
"when",
"q",
"pinkie",
"lie",
"vow"]
var i = 0, len = libs.length
for(; i < len; i++){
try {
return loadImplementation(libs[i])
} catch(e){}
}
return null
}
|
javascript
|
{
"resource": ""
}
|
q52262
|
Request
|
train
|
function Request(url, options) {
if (!url) {
throw new Error('URL must in mandatory to initialize Request object');
}
if (!options.method) {
throw new Error('Cannot execute HTTP request without specifying method');
}
this.url = url;
this.method = options.method;
this.body = options.body || {};
this.params = options.params || {};
this.path = options.path || null;
this.headers = options.headers || {};
this.dataType = (options.dataType === undefined) ? 'json' : options.dataType;
this.auth = options.auth || {};
this.cache = options.cache || { cache: false, expires: 3600 };
this.timeout = options.timeout || 30000;
this.cookies(options.cookies);
this.redirect = options.redirect || false
}
|
javascript
|
{
"resource": ""
}
|
q52263
|
Response
|
train
|
function Response(code, headers, body) {
this.code = code;
this.headers = headers;
this.body = body || '';
}
|
javascript
|
{
"resource": ""
}
|
q52264
|
compileBundle
|
train
|
function compileBundle(_ref) {
var customWebConfig = _ref.customWebConfig,
architecture = _ref.architecture;
var workingDir = _tmp.default.dirSync().name;
_winston.default.info('Compiling application bundle'); // Generate Meteor build
_winston.default.debug('generate meteor build');
_shelljs.default.exec(`meteor build ${workingDir} --directory --server-only --architecture os.windows.x86_${architecture}`); // Add custom web config
if (customWebConfig !== undefined) {
_winston.default.debug('add custom web config');
try {
_shelljs.default.cp(customWebConfig, _path.default.join(workingDir, 'bundle', 'web.config'));
} catch (error) {
throw new Error(`Could not read web config file at '${customWebConfig}'`);
}
} else {
_winston.default.warn('Using default web config');
} // Cleanup broken symlinks
_winston.default.debug('checking for broken symlinks');
_shelljs.default.find(_path.default.join(workingDir, 'bundle')).forEach(function (symlinkPath) {
// Matches symlinks that do not exist
if (_shelljs.default.test('-L', symlinkPath) && !_shelljs.default.test('-e', symlinkPath)) {
// Delete file
_shelljs.default.rm('-f', symlinkPath);
_winston.default.debug(`deleted symlink at '${symlinkPath}'`);
}
}); // Create tarball
_winston.default.debug('create tarball');
var tarballPath = _path.default.join(workingDir, 'bundle.tar.gz');
_tar.default.c({
file: tarballPath,
sync: true,
follow: true,
gzip: true,
cwd: workingDir
}, ['bundle']);
return tarballPath;
}
|
javascript
|
{
"resource": ""
}
|
q52265
|
loadFile
|
train
|
function loadFile(fullFilePath, callback) {
fs.readFile(fullFilePath, "utf-8", function(err, data) {
if (err) {
return callback(err);
}
return callback(null, data);
});
}
|
javascript
|
{
"resource": ""
}
|
q52266
|
handleFile
|
train
|
function handleFile(name, file, options, cache, callback) {
var cachedData;
if(!options || !options.settings || options.settings['view cache'] !== false) {
cachedData = cache && cache.get(file);
}
if (!cachedData) {
loadFile(file, function(err, fileData) {
if (err) {
return callback(err);
}
var partials;
try {
partials = findPartials(fileData);
} catch (err) {
return callback(err);
}
var data = {
name: name,
data: fileData,
partials: partials
};
if (cache) {
cache.set(file, data);
}
return callback(null, data);
});
}
else {
return callback(null, cachedData);
}
}
|
javascript
|
{
"resource": ""
}
|
q52267
|
consolidatePartials
|
train
|
function consolidatePartials(arr) {
var partialsSet = {};
arr.forEach(function(item) {
item.partials.forEach(function(partial) {
partialsSet[partial] = true;
});
});
return Object.keys(partialsSet);
}
|
javascript
|
{
"resource": ""
}
|
q52268
|
loadAllPartials
|
train
|
function loadAllPartials(unparsedPartials, partialsDirectory, partialsExtension, options, cache, partials, callback) {
if (!partials) {
partials = {};
}
// This function is called recursively. This is our base case: the point where we
// don't call recursively anymore.
// That point is when there are no partials that need to be parsed.
if (unparsedPartials.length === 0) {
return callback(null, partials);
}
async.map(unparsedPartials, function(partial, next) {
var fullFilePath;
if('function' === typeof partialsDirectory){
fullFilePath = partialsDirectory(partial,partialsExtension);
} else {
fullFilePath = path.resolve(partialsDirectory, partial + partialsExtension);
}
return handleFile(partial, fullFilePath, options, cache, next);
}, function(err, data) {
if (err) {
return callback(err);
}
// Add all of the data to the 'partials' object
data.forEach(function(partialData) {
partials[partialData.name] = partialData.data;
});
// Get all of the partials that are referenced by the data we've loaded
var consolidatedPartials = consolidatePartials(data);
// Get all of the partials that we haven't loaded yet.
var partialsToLoad = findUnloadedPartials(consolidatedPartials, partials);
// Recursive call.
return loadAllPartials(partialsToLoad, partialsDirectory, partialsExtension, options, cache, partials, callback);
});
}
|
javascript
|
{
"resource": ""
}
|
q52269
|
loadTemplateAndPartials
|
train
|
function loadTemplateAndPartials(templateFile, partialsDirectory, partialsExtension, options, cache, callback) {
handleFile(null, templateFile, options, cache, function(err, partialData) {
if (err) {
return callback(err);
}
return loadAllPartials(partialData.partials, partialsDirectory, partialsExtension, options, cache, null, function(err, partials) {
if (err) {
return callback(err);
}
return callback(null, partialData.data, partials);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q52270
|
train
|
function(consumerKey, done) {
db.clients.findByConsumerKey(consumerKey, function(err, client) {
if (err) { return done(err); }
if (!client) { return done(null, false); }
return done(null, client, client.consumerSecret);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q52271
|
train
|
function(requestToken, done) {
db.requestTokens.find(requestToken, function(err, token) {
if (err) { return done(err); }
var info = { verifier: token.verifier,
clientID: token.clientID,
userID: token.userID,
approved: token.approved
}
done(null, token.secret, info);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q52272
|
train
|
function(config) {
if (!config) {
return [];
}
var files = grunt.file.expand(config);
if (files.length) {
return files;
}
return [config];
}
|
javascript
|
{
"resource": ""
}
|
|
q52273
|
train
|
function(data, dontParse) {
// grunt.file chokes on objects, so we check for it immiedietly
if (typeof data === 'object') {
return data;
}
// `data` isn't an object, so its probably a file
try {
// alce allows us to parse single-quote JSON (which is tehcnically invalid, and thereby chokes JSON.parse)
data = grunt.file.read(data);
if (!dontParse) {
data = alce.parse(data);
}
}
catch (e) {}
return data;
}
|
javascript
|
{
"resource": ""
}
|
|
q52274
|
train
|
function(filename) {
if (!filename || typeof filename === 'object') {
return;
}
var match = filename.match(/[^\*]*/);
if (match[0] !== filename) {
return match.pop();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52275
|
train
|
function(filename, template, outputInInput) {
var basename;
var glob;
template = Array.isArray(template) ? filename : template;
glob = isGlob(template);
if (outputInInput) {
basename = _toArray(filename.split('.').pop()) ;
} else if (glob) {
basename = filename.slice(glob.length, filename.length).split('.');
basename.pop();
} else {
basename = filename.split('/').pop().split('.');
basename.pop();
}
return basename.join('.');
}
|
javascript
|
{
"resource": ""
}
|
|
q52276
|
calculateXAlign
|
train
|
function calculateXAlign (windowBounds, trayBounds, align) {
const display = getDisplay()
let x
switch (align) {
case 'right':
x = trayBounds.x
break
case 'left':
x = trayBounds.x + trayBounds.width - windowBounds.width
break
case 'center':
default:
x = Math.round(trayBounds.x + (trayBounds.width / 2) - (windowBounds.width / 2))
}
if (x + windowBounds.width > display.bounds.width && align !== 'left') {
// if window would overlap on right side align it to the end of the screen
x = display.bounds.width - windowBounds.width
} else if (x < 0 && align !== 'right') {
// if window would overlap on the left side align it to the beginning
x = 0
}
return x
}
|
javascript
|
{
"resource": ""
}
|
q52277
|
calculateYAlign
|
train
|
function calculateYAlign (windowBounds, trayBounds, align) {
const display = getDisplay()
let y
switch (align) {
case 'up':
y = trayBounds.y + trayBounds.height - windowBounds.height
break
case 'down':
y = trayBounds.y
break
case 'center':
default:
y = Math.round((trayBounds.y + (trayBounds.height / 2)) - (windowBounds.height / 2))
break
}
if (y + windowBounds.height > display.bounds.height && align !== 'up') {
y = trayBounds.y + trayBounds.height - windowBounds.height
} else if (y < 0 && align !== 'down') {
y = 0
}
return y
}
|
javascript
|
{
"resource": ""
}
|
q52278
|
calculateByCursorPosition
|
train
|
function calculateByCursorPosition (windowBounds, display, cursor) {
let x = cursor.x
let y = cursor.y
if (x + windowBounds.width > display.bounds.width) {
// if window would overlap on right side of screen, align it to the left of the cursor
x -= windowBounds.width
}
if (y + windowBounds.height > display.bounds.height) {
// if window would overlap at bottom of screen, align it up from cursor position
y -= windowBounds.height
}
return {
x: x,
y: y
}
}
|
javascript
|
{
"resource": ""
}
|
q52279
|
detectBrowser
|
train
|
function detectBrowser (browsers, browserQuery) {
var b = false;
browserQuery = browserslist(browserQuery);
for (var i = 0; i < browsers.length; i++) {
for (var j = 0; j < browserQuery.length; j++) {
if (browsers[i] === browserQuery[j]) {
b = true;
break;
}
}
if (b) { break; }
}
return b;
}
|
javascript
|
{
"resource": ""
}
|
q52280
|
toPx
|
train
|
function toPx (value, decl, result) {
value = (typeof value === 'string' && value.indexOf('calc(') !== -1) ? calc(value) : value;
var parts = /^(\d*\.?\d+)([a-zA-Z%]*)$/.exec(value);
if (parts !== null) {
var number = parts[1];
var unit = parts[2];
if (unit === 'px' || unit === '') {
return parseFloat(number);
}
else if (unit === 'em' || unit === 'rem') {
return parseFloat(number) * BASE_FONT_SIZE;
}
else if (unit === '%') {
return (parseFloat(number) / 100) * BASE_FONT_SIZE;
} else {
// other units: vw, ex, ch, etc...
result.warn('Unit cannot be used for conversion, so 16px is used.');
return BASE_FONT_SIZE;
}
} else {
throw decl.error('Root font-size is invalid', {plugin: 'pixrem'});
}
}
|
javascript
|
{
"resource": ""
}
|
q52281
|
iterInit
|
train
|
function iterInit(d, count) {
var levels = (8 * bits.log2(count+1) * (d+1))|0
var maxInts = bits.nextPow2(IFRAME_SIZE*levels)
if(BOX_ISTACK.length < maxInts) {
pool.free(BOX_ISTACK)
BOX_ISTACK = pool.mallocInt32(maxInts)
}
var maxDoubles = bits.nextPow2(DFRAME_SIZE*levels)
if(BOX_DSTACK.length < maxDoubles) {
pool.free(BOX_DSTACK)
BOX_DSTACK = pool.mallocDouble(maxDoubles)
}
}
|
javascript
|
{
"resource": ""
}
|
q52282
|
iterPush
|
train
|
function iterPush(ptr,
axis,
redStart, redEnd,
blueStart, blueEnd,
state,
lo, hi) {
var iptr = IFRAME_SIZE * ptr
BOX_ISTACK[iptr] = axis
BOX_ISTACK[iptr+1] = redStart
BOX_ISTACK[iptr+2] = redEnd
BOX_ISTACK[iptr+3] = blueStart
BOX_ISTACK[iptr+4] = blueEnd
BOX_ISTACK[iptr+5] = state
var dptr = DFRAME_SIZE * ptr
BOX_DSTACK[dptr] = lo
BOX_DSTACK[dptr+1] = hi
}
|
javascript
|
{
"resource": ""
}
|
q52283
|
convertBoxes
|
train
|
function convertBoxes(boxes, d, data, ids) {
var ptr = 0
var count = 0
for(var i=0, n=boxes.length; i<n; ++i) {
var b = boxes[i]
if(boxEmpty(d, b)) {
continue
}
for(var j=0; j<2*d; ++j) {
data[ptr++] = b[j]
}
ids[count++] = i
}
return count
}
|
javascript
|
{
"resource": ""
}
|
q52284
|
boxIntersect
|
train
|
function boxIntersect(red, blue, visit, full) {
var n = red.length
var m = blue.length
//If either array is empty, then we can skip this whole thing
if(n <= 0 || m <= 0) {
return
}
//Compute dimension, if it is 0 then we skip
var d = (red[0].length)>>>1
if(d <= 0) {
return
}
var retval
//Convert red boxes
var redList = pool.mallocDouble(2*d*n)
var redIds = pool.mallocInt32(n)
n = convertBoxes(red, d, redList, redIds)
if(n > 0) {
if(d === 1 && full) {
//Special case: 1d complete
sweep.init(n)
retval = sweep.sweepComplete(
d, visit,
0, n, redList, redIds,
0, n, redList, redIds)
} else {
//Convert blue boxes
var blueList = pool.mallocDouble(2*d*m)
var blueIds = pool.mallocInt32(m)
m = convertBoxes(blue, d, blueList, blueIds)
if(m > 0) {
sweep.init(n+m)
if(d === 1) {
//Special case: 1d bipartite
retval = sweep.sweepBipartite(
d, visit,
0, n, redList, redIds,
0, m, blueList, blueIds)
} else {
//General case: d>1
retval = boxIntersectIter(
d, visit, full,
n, redList, redIds,
m, blueList, blueIds)
}
pool.free(blueList)
pool.free(blueIds)
}
}
pool.free(redList)
pool.free(redIds)
}
return retval
}
|
javascript
|
{
"resource": ""
}
|
q52285
|
boxIntersectWrapper
|
train
|
function boxIntersectWrapper(arg0, arg1, arg2) {
var result
switch(arguments.length) {
case 1:
return intersectFullArray(arg0)
case 2:
if(typeof arg1 === 'function') {
return boxIntersect(arg0, arg0, arg1, true)
} else {
return intersectBipartiteArray(arg0, arg1)
}
case 3:
return boxIntersect(arg0, arg1, arg2, false)
default:
throw new Error('box-intersect: Invalid arguments')
}
}
|
javascript
|
{
"resource": ""
}
|
q52286
|
sqInit
|
train
|
function sqInit(count) {
var rcount = bits.nextPow2(count)
if(RED_SWEEP_QUEUE.length < rcount) {
pool.free(RED_SWEEP_QUEUE)
RED_SWEEP_QUEUE = pool.mallocInt32(rcount)
}
if(RED_SWEEP_INDEX.length < rcount) {
pool.free(RED_SWEEP_INDEX)
RED_SWEEP_INDEX = pool.mallocInt32(rcount)
}
if(BLUE_SWEEP_QUEUE.length < rcount) {
pool.free(BLUE_SWEEP_QUEUE)
BLUE_SWEEP_QUEUE = pool.mallocInt32(rcount)
}
if(BLUE_SWEEP_INDEX.length < rcount) {
pool.free(BLUE_SWEEP_INDEX)
BLUE_SWEEP_INDEX = pool.mallocInt32(rcount)
}
if(COMMON_SWEEP_QUEUE.length < rcount) {
pool.free(COMMON_SWEEP_QUEUE)
COMMON_SWEEP_QUEUE = pool.mallocInt32(rcount)
}
if(COMMON_SWEEP_INDEX.length < rcount) {
pool.free(COMMON_SWEEP_INDEX)
COMMON_SWEEP_INDEX = pool.mallocInt32(rcount)
}
var eventLength = 8 * rcount
if(SWEEP_EVENTS.length < eventLength) {
pool.free(SWEEP_EVENTS)
SWEEP_EVENTS = pool.mallocDouble(eventLength)
}
}
|
javascript
|
{
"resource": ""
}
|
q52287
|
train
|
function (delta) {
var currentPose;
var currentEvent
var playingPoses = this.playingPoses;
var playingEvents = this.playingEvents;
currentPose = playingPoses && playingPoses[this.currentPoseIndex]
currentEvent = playingEvents && playingEvents[this.currentEventIndex];
this.currentPoseTime += delta;
this.currentEventTime += delta;
// Determine next pose.
// Comparing currentPoseTime to currentEvent.timestamp is not a typo.
while ((currentPose && this.currentPoseTime >= currentPose.timestamp) ||
(currentEvent && this.currentPoseTime >= currentEvent.timestamp)) {
// Pose.
if (currentPose && this.currentPoseTime >= currentPose.timestamp) {
if (this.currentPoseIndex === playingPoses.length - 1) {
if (this.data.loop) {
this.currentPoseIndex = 0;
this.currentPoseTime = playingPoses[0].timestamp;
} else {
this.stopReplaying();
}
}
applyPose(this.el, currentPose);
this.currentPoseIndex += 1;
currentPose = playingPoses[this.currentPoseIndex];
}
// Event.
if (currentEvent && this.currentPoseTime >= currentEvent.timestamp) {
if (this.currentEventIndex === playingEvents.length && this.data.loop) {
this.currentEventIndex = 0;
this.currentEventTime = playingEvents[0].timestamp;
}
this.el.emit(currentEvent.name, currentEvent.detail);
this.currentEventIndex += 1;
currentEvent = this.playingEvents[this.currentEventIndex];
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52288
|
train
|
function () {
var data = this.data;
var sceneEl = this.el;
if (data.cameraOverride) {
// Specify which camera is the original camera (e.g., used by Inspector).
this.cameraEl = data.cameraOverride;
} else {
// Default camera.
this.cameraEl = sceneEl.camera.el;
// Make sure A-Frame doesn't automatically remove this camera.
this.cameraEl.removeAttribute('data-aframe-default-camera');
}
this.cameraEl.setAttribute('data-aframe-avatar-replayer-camera', '');
sceneEl.removeEventListener('camera-set-active', this.setupCamera);
this.configureHeadGeometry();
// Create spectator camera for either if we are in spectator mode or toggling to it.
this.initSpectatorCamera();
}
|
javascript
|
{
"resource": ""
}
|
|
q52289
|
train
|
function () {
var spectatorCameraEl = this.spectatorCameraEl;
if (!spectatorCameraEl) {
this.el.addEventListener('spectatorcameracreated',
bind(this.activateSpectatorCamera, this));
return;
}
if (!spectatorCameraEl.hasLoaded) {
spectatorCameraEl.addEventListener('loaded', bind(this.activateSpectatorCamera, this));
return;
}
log('Activating spectator camera');
spectatorCameraEl.setAttribute('camera', 'active', true);
this.cameraEl.getObject3D('replayerMesh').visible = true;
}
|
javascript
|
{
"resource": ""
}
|
|
q52290
|
train
|
function () {
var data = this.data;
var sceneEl = this.el;
var spectatorCameraEl;
var spectatorCameraRigEl;
// Developer-defined spectator rig.
if (this.el.querySelector('#spectatorCameraRig')) {
this.spectatorCameraEl = sceneEl.querySelector('#spectatorCameraRig');
return;
}
// Create spectator camera rig.
spectatorCameraRigEl = sceneEl.querySelector('#spectatorCameraRig') ||
document.createElement('a-entity');
spectatorCameraRigEl.id = 'spectatorCameraRig';
spectatorCameraRigEl.setAttribute('position', data.spectatorPosition);
this.spectatorCameraRigEl = spectatorCameraRigEl;
// Create spectator camera.
spectatorCameraEl = sceneEl.querySelector('#spectatorCamera') ||
document.createElement('a-entity');
spectatorCameraEl.id = 'spectatorCamera';
spectatorCameraEl.setAttribute('camera', {active: data.spectatorMode, userHeight: 0});
spectatorCameraEl.setAttribute('look-controls', '');
spectatorCameraEl.setAttribute('wasd-controls', {fly: true});
this.spectatorCameraEl = spectatorCameraEl;
// Append rig.
spectatorCameraRigEl.appendChild(spectatorCameraEl);
sceneEl.appendChild(spectatorCameraRigEl);
sceneEl.emit('spectatorcameracreated');
}
|
javascript
|
{
"resource": ""
}
|
|
q52291
|
train
|
function () {
var data = this.data;
var recordingdb = this.el.systems.recordingdb;;
var recordingNames;
var src;
var self = this;
// Allow override to display replayer from query param.
if (new URLSearchParams(window.location.search).get('avatar-replayer-disabled') !== null) {
return;
}
recordingdb.getRecordingNames().then(function (recordingNames) {
// See if recording defined in query parameter.
var queryParamSrc = self.getSrcFromSearchParam();
// 1. Try `avatar-recorder` query parameter as recording name from IndexedDB.
if (recordingNames.indexOf(queryParamSrc) !== -1) {
log('Replaying `' + queryParamSrc + '` from IndexedDB.');
recordingdb.getRecording(queryParamSrc).then(bind(self.startReplaying, self));
return;
}
// 2. Use `avatar-recorder` query parameter or `data.src` as URL.
src = queryParamSrc || self.data.src;
if (src) {
if (self.data.src) {
log('Replaying from component `src`', src);
} else if (queryParamSrc) {
log('Replaying from query parameter `recording`', src);
}
self.loadRecordingFromUrl(src, false, bind(self.startReplaying, self));
return;
}
// 3. Use `data.recordingName` as recording name from IndexedDB.
if (recordingNames.indexOf(self.data.recordingName) !== -1) {
log('Replaying `' + self.data.recordingName + '` from IndexedDB.');
recordingdb.getRecording(self.data.recordingName).then(bind(self.startReplaying, self));
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q52292
|
train
|
function () {
var cameraEl = this.cameraEl;
var headMesh;
var leftEyeMesh;
var rightEyeMesh;
var leftEyeBallMesh;
var rightEyeBallMesh;
if (cameraEl.getObject3D('mesh') || cameraEl.getObject3D('replayerMesh')) { return; }
// Head.
headMesh = new THREE.Mesh();
headMesh.geometry = new THREE.BoxBufferGeometry(0.3, 0.3, 0.2);
headMesh.material = new THREE.MeshStandardMaterial({color: 'pink'});
headMesh.visible = this.data.spectatorMode;
// Left eye.
leftEyeMesh = new THREE.Mesh();
leftEyeMesh.geometry = new THREE.SphereBufferGeometry(0.05);
leftEyeMesh.material = new THREE.MeshBasicMaterial({color: 'white'});
leftEyeMesh.position.x -= 0.1;
leftEyeMesh.position.y += 0.1;
leftEyeMesh.position.z -= 0.1;
leftEyeBallMesh = new THREE.Mesh();
leftEyeBallMesh.geometry = new THREE.SphereBufferGeometry(0.025);
leftEyeBallMesh.material = new THREE.MeshBasicMaterial({color: 'black'});
leftEyeBallMesh.position.z -= 0.04;
leftEyeMesh.add(leftEyeBallMesh);
headMesh.add(leftEyeMesh);
// Right eye.
rightEyeMesh = new THREE.Mesh();
rightEyeMesh.geometry = new THREE.SphereBufferGeometry(0.05);
rightEyeMesh.material = new THREE.MeshBasicMaterial({color: 'white'});
rightEyeMesh.position.x += 0.1;
rightEyeMesh.position.y += 0.1;
rightEyeMesh.position.z -= 0.1;
rightEyeBallMesh = new THREE.Mesh();
rightEyeBallMesh.geometry = new THREE.SphereBufferGeometry(0.025);
rightEyeBallMesh.material = new THREE.MeshBasicMaterial({color: 'black'});
rightEyeBallMesh.position.z -= 0.04;
rightEyeMesh.add(rightEyeBallMesh);
headMesh.add(rightEyeMesh);
cameraEl.setObject3D('replayerMesh', headMesh);
}
|
javascript
|
{
"resource": ""
}
|
|
q52293
|
train
|
function () {
var self = this;
if (!this.isReplaying || !this.replayData) { return; }
this.isReplaying = false;
Object.keys(this.replayData).forEach(function removeReplayer (key) {
if (key === 'camera') {
self.cameraEl.removeComponent('motion-capture-replayer');
} else {
el = document.querySelector('#' + key);
if (!el) {
warn('No element with id ' + key);
return;
}
el.removeComponent('motion-capture-replayer');
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q52294
|
train
|
function (url, binary, callback) {
var data;
var self = this;
fileLoader.crossOrigin = 'anonymous';
if (binary === true) {
fileLoader.setResponseType('arraybuffer');
}
fileLoader.load(url, function (buffer) {
if (binary === true) {
data = self.loadStrokeBinary(buffer);
} else {
data = JSON.parse(buffer);
}
if (callback) { callback(data); }
});
}
|
javascript
|
{
"resource": ""
}
|
|
q52295
|
train
|
function () {
var self = this;
var trackedControllerEls = this.el.querySelectorAll('[tracked-controls]');
this.trackedControllerEls = {};
trackedControllerEls.forEach(function setupController (trackedControllerEl) {
if (!trackedControllerEl.id) {
warn('Found a tracked controller entity without an ID. ' +
'Provide an ID or this controller will not be recorded');
return;
}
trackedControllerEl.setAttribute('motion-capture-recorder', {
autoRecord: false,
visibleStroke: false
});
self.trackedControllerEls[trackedControllerEl.id] = trackedControllerEl;
if (self.isRecording) {
trackedControllerEl.components['motion-capture-recorder'].startRecording();
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q52296
|
train
|
function (evt) {
var key = evt.keyCode;
var KEYS = {space: 32};
switch (key) {
// <space>: Toggle recording.
case KEYS.space: {
this.toggleRecording();
break;
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52297
|
train
|
function (doneCb) {
var el = this.el;
var self = this;
if (this.data.cameraOverride) {
prepareCamera(this.data.cameraOverride);
return;
}
// Grab camera.
if (el.camera && el.camera.el) {
prepareCamera(el.camera.el);
return;
}
el.addEventListener('camera-set-active', function setup (evt) {
prepareCamera(evt.detail.cameraEl);
el.removeEventListener('camera-set-active', setup);
});
function prepareCamera (cameraEl) {
if (self.cameraEl) {
self.cameraEl.removeAttribute('motion-capture-recorder');
}
self.cameraEl = cameraEl;
cameraEl.setAttribute('motion-capture-recorder', {
autoRecord: false,
visibleStroke: false
});
doneCb(cameraEl)
}
}
|
javascript
|
{
"resource": ""
}
|
|
q52298
|
train
|
function () {
var trackedControllerEls = this.trackedControllerEls;
var self = this;
if (this.isRecording) { return; }
log('Starting recording!');
if (this.el.components['avatar-replayer']) {
this.el.components['avatar-replayer'].stopReplaying();
}
// Get camera.
this.setupCamera(function cameraSetUp () {
self.isRecording = true;
// Record camera.
self.cameraEl.components['motion-capture-recorder'].startRecording();
// Record tracked controls.
Object.keys(trackedControllerEls).forEach(function startRecordingController (id) {
trackedControllerEls[id].components['motion-capture-recorder'].startRecording();
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q52299
|
train
|
function () {
var trackedControllerEls = this.trackedControllerEls;
if (!this.isRecording) { return; }
log('Stopped recording.');
this.isRecording = false;
this.cameraEl.components['motion-capture-recorder'].stopRecording();
Object.keys(trackedControllerEls).forEach(function (id) {
trackedControllerEls[id].components['motion-capture-recorder'].stopRecording();
});
this.recordingData = this.getJSONData();
this.storeRecording(this.recordingData);
if (this.data.autoPlay) {
this.replayRecording();
}
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.