_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q24500 | createPredicateFn | train | function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
var predicateFn;
if (comparator === true) {
comparator = equals;
} else if (!isFunction(comparator)) {
comparator = function(actual, expected) {
if (isObject(actual) || isObject(expected)) {
// Prevent an object to be considered equal to a string like `'[object'`
return false;
}
actual = lowercase('' + actual);
expected = lowercase('' + expected);
return actual.indexOf(expected) !== -1;
};
}
predicateFn = function(item) {
return deepCompare(item, expression, comparator, matchAgainstAnyProp);
};
return predicateFn;
} | javascript | {
"resource": ""
} |
q24501 | regExpPrefix | train | function regExpPrefix(re) {
var prefix = /^\^((?:\\[^a-zA-Z0-9]|[^\\\[\]\^$*+?.()|{}]+)*)/.exec(re.source);
return (prefix != null) ? prefix[1].replace(/\\(.)/g, "$1") : '';
} | javascript | {
"resource": ""
} |
q24502 | train | function(scope, element, attr) {
attr.$observe(ngAttrName, function(value) {
if (!value) {
element[0].removeAttribute(attrName);
}
});
} | javascript | {
"resource": ""
} | |
q24503 | onContentTap | train | function onContentTap(gestureEvt) {
if (sideMenuCtrl.getOpenAmount() !== 0) {
sideMenuCtrl.close();
gestureEvt.gesture.srcEvent.preventDefault();
startCoord = null;
primaryScrollAxis = null;
} else if (!startCoord) {
startCoord = ionic.tap.pointerCoord(gestureEvt.gesture.srcEvent);
}
} | javascript | {
"resource": ""
} |
q24504 | sortedColumnClasses | train | function sortedColumnClasses(classes) {
// extract column classes
var colClasses = [];
while (true) {
var match = COL_REGEX.exec(classes);
if (!match) {
break;
}
var colClass = match[0];
colClasses.push(colClass);
classes = withoutClass(classes, colClass);
}
colClasses.sort(compareColumnClasses);
return classes + ' ' + colClasses.join(' ');
} | javascript | {
"resource": ""
} |
q24505 | LocationIndex | train | function LocationIndex(string) {
// ensure newline termination
if (string[string.length - 1] !== '\n') {
string += '\n';
}
this._stringLength = string.length;
/*
* Each triple in _lineStartEndTriples consists of:
* [0], the 0-based line index of the line the triple represents
* [1], the 0-based code unit index (into the string) of the start of the line (inclusive)
* [2], the 0-based code unit index (into the string) of the start of the next line (or the length of the string, if it is the last line)
* A line starts with a non-newline character,
* and always ends in a newline character, unless it is the very last line in the string.
*/
this._lineStartEndTriples = [[0, 0]];
var nextLineIndex = 1;
var charIndex = 0;
while (charIndex < string.length) {
charIndex = string.indexOf('\n', charIndex);
if (charIndex === -1) {
/* istanbul ignore next */
break;
}
charIndex++;// go past the newline
this._lineStartEndTriples[this._lineStartEndTriples.length - 1].push(charIndex);
this._lineStartEndTriples.push([nextLineIndex, charIndex]);
nextLineIndex++;
}
this._lineStartEndTriples.pop();
} | javascript | {
"resource": ""
} |
q24506 | w | train | function w(d, outer) {
var width = self.options.cellSize*self._domainType[self.options.subDomain].column(d) + self.options.cellPadding*self._domainType[self.options.subDomain].column(d);
if (arguments.length === 2 && outer === true) {
return width += self.domainHorizontalLabelWidth + self.options.domainGutter + self.options.domainMargin[1] + self.options.domainMargin[3];
}
return width;
} | javascript | {
"resource": ""
} |
q24507 | h | train | function h(d, outer) {
var height = self.options.cellSize*self._domainType[self.options.subDomain].row(d) + self.options.cellPadding*self._domainType[self.options.subDomain].row(d);
if (arguments.length === 2 && outer === true) {
height += self.options.domainGutter + self.domainVerticalLabelHeight + self.options.domainMargin[0] + self.options.domainMargin[2];
}
return height;
} | javascript | {
"resource": ""
} |
q24508 | validateSelector | train | function validateSelector(selector, canBeFalse, name) {
if (((canBeFalse && selector === false) || selector instanceof Element || typeof selector === "string") && selector !== "") {
return true;
}
throw new Error("The " + name + " is not valid");
} | javascript | {
"resource": ""
} |
q24509 | validateDomainType | train | function validateDomainType() {
if (!parent._domainType.hasOwnProperty(options.domain) || options.domain === "min" || options.domain.substring(0, 2) === "x_") {
throw new Error("The domain '" + options.domain + "' is not valid");
}
if (!parent._domainType.hasOwnProperty(options.subDomain) || options.subDomain === "year") {
throw new Error("The subDomain '" + options.subDomain + "' is not valid");
}
if (parent._domainType[options.domain].level <= parent._domainType[options.subDomain].level) {
throw new Error("'" + options.subDomain + "' is not a valid subDomain to '" + options.domain + "'");
}
return true;
} | javascript | {
"resource": ""
} |
q24510 | autoAlignLabel | train | function autoAlignLabel() {
// Auto-align label, depending on it's position
if (!settings.hasOwnProperty("label") || (settings.hasOwnProperty("label") && !settings.label.hasOwnProperty("align"))) {
switch(options.label.position) {
case "left":
options.label.align = "right";
break;
case "right":
options.label.align = "left";
break;
default:
options.label.align = "center";
}
if (options.label.rotate === "left") {
options.label.align = "right";
} else if (options.label.rotate === "right") {
options.label.align = "left";
}
}
if (!settings.hasOwnProperty("label") || (settings.hasOwnProperty("label") && !settings.label.hasOwnProperty("offset"))) {
if (options.label.position === "left" || options.label.position === "right") {
options.label.offset = {
x: 10,
y: 15
};
}
}
} | javascript | {
"resource": ""
} |
q24511 | autoAddLegendMargin | train | function autoAddLegendMargin() {
switch(options.legendVerticalPosition) {
case "top":
options.legendMargin[2] = parent.DEFAULT_LEGEND_MARGIN;
break;
case "bottom":
options.legendMargin[0] = parent.DEFAULT_LEGEND_MARGIN;
break;
case "middle":
case "center":
options.legendMargin[options.legendHorizontalPosition === "right" ? 3 : 1] = parent.DEFAULT_LEGEND_MARGIN;
}
} | javascript | {
"resource": ""
} |
q24512 | expandMarginSetting | train | function expandMarginSetting(value) {
if (typeof value === "number") {
value = [value];
}
if (!Array.isArray(value)) {
console.log("Margin only takes an integer or an array of integers");
value = [0];
}
switch(value.length) {
case 1:
return [value[0], value[0], value[0], value[0]];
case 2:
return [value[0], value[1], value[0], value[1]];
case 3:
return [value[0], value[1], value[2], value[1]];
case 4:
return value;
default:
return value.slice(0, 4);
}
} | javascript | {
"resource": ""
} |
q24513 | addStyle | train | function addStyle(element) {
if (parent.legendScale === null) {
return false;
}
element.attr("fill", function(d) {
if (d.v === null && (options.hasOwnProperty("considerMissingDataAsZero") && !options.considerMissingDataAsZero)) {
if (options.legendColors.hasOwnProperty("base")) {
return options.legendColors.base;
}
}
if (options.legendColors !== null && options.legendColors.hasOwnProperty("empty") &&
(d.v === 0 || (d.v === null && options.hasOwnProperty("considerMissingDataAsZero") && options.considerMissingDataAsZero))
) {
return options.legendColors.empty;
}
if (d.v < 0 && options.legend[0] > 0 && options.legendColors !== null && options.legendColors.hasOwnProperty("overflow")) {
return options.legendColors.overflow;
}
return parent.legendScale(Math.min(d.v, options.legend[options.legend.length-1]));
});
} | javascript | {
"resource": ""
} |
q24514 | train | function(start) {
"use strict";
var parent = this;
return this.triggerEvent("afterLoadPreviousDomain", function() {
var subDomain = parent.getSubDomain(start);
return [subDomain.shift(), subDomain.pop()];
});
} | javascript | {
"resource": ""
} | |
q24515 | train | function(n) {
"use strict";
if (this._minDomainReached || n === 0) {
return false;
}
var bound = this.loadNewDomains(this.NAVIGATE_LEFT, this.getDomain(this.getDomainKeys()[0], -n).reverse());
this.afterLoadPreviousDomain(bound.start);
this.checkIfMinDomainIsReached(bound.start, bound.end);
return true;
} | javascript | {
"resource": ""
} | |
q24516 | train | function() {
"use strict";
return this._domains.keys()
.map(function(d) { return parseInt(d, 10); })
.sort(function(a,b) { return a-b; });
} | javascript | {
"resource": ""
} | |
q24517 | train | function(d) {
"use strict";
d = new Date(d);
if (this.options.highlight.length > 0) {
for (var i in this.options.highlight) {
if (this.dateIsEqual(this.options.highlight[i], d)) {
return this.isNow(this.options.highlight[i]) ? " highlight-now": " highlight";
}
}
}
return "";
} | javascript | {
"resource": ""
} | |
q24518 | train | function(dateA, dateB) {
"use strict";
if(!(dateA instanceof Date)) {
dateA = new Date(dateA);
}
if (!(dateB instanceof Date)) {
dateB = new Date(dateB);
}
switch(this.options.subDomain) {
case "x_min":
case "min":
return dateA.getFullYear() === dateB.getFullYear() &&
dateA.getMonth() === dateB.getMonth() &&
dateA.getDate() === dateB.getDate() &&
dateA.getHours() === dateB.getHours() &&
dateA.getMinutes() === dateB.getMinutes();
case "x_hour":
case "hour":
return dateA.getFullYear() === dateB.getFullYear() &&
dateA.getMonth() === dateB.getMonth() &&
dateA.getDate() === dateB.getDate() &&
dateA.getHours() === dateB.getHours();
case "x_day":
case "day":
return dateA.getFullYear() === dateB.getFullYear() &&
dateA.getMonth() === dateB.getMonth() &&
dateA.getDate() === dateB.getDate();
case "x_week":
case "week":
return dateA.getFullYear() === dateB.getFullYear() &&
this.getWeekNumber(dateA) === this.getWeekNumber(dateB);
case "x_month":
case "month":
return dateA.getFullYear() === dateB.getFullYear() &&
dateA.getMonth() === dateB.getMonth();
default:
return false;
}
} | javascript | {
"resource": ""
} | |
q24519 | train | function(dateA, dateB) {
"use strict";
if(!(dateA instanceof Date)) {
dateA = new Date(dateA);
}
if (!(dateB instanceof Date)) {
dateB = new Date(dateB);
}
function normalizedMillis(date, subdomain) {
switch(subdomain) {
case "x_min":
case "min":
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes()).getTime();
case "x_hour":
case "hour":
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours()).getTime();
case "x_day":
case "day":
return new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
case "x_week":
case "week":
case "x_month":
case "month":
return new Date(date.getFullYear(), date.getMonth()).getTime();
default:
return date.getTime();
}
}
return normalizedMillis(dateA, this.options.subDomain) < normalizedMillis(dateB, this.options.subDomain);
} | javascript | {
"resource": ""
} | |
q24520 | train | function(d) {
"use strict";
var f = this.options.weekStartOnMonday === true ? d3.time.format("%W"): d3.time.format("%U");
return f(d);
} | javascript | {
"resource": ""
} | |
q24521 | train | function (d) {
"use strict";
if (typeof d === "number") {
d = new Date(d);
}
var monthFirstWeekNumber = this.getWeekNumber(new Date(d.getFullYear(), d.getMonth()));
return this.getWeekNumber(d) - monthFirstWeekNumber - 1;
} | javascript | {
"resource": ""
} | |
q24522 | train | function(d) {
"use strict";
if (this.options.weekStartOnMonday === false) {
return d.getDay();
}
return d.getDay() === 0 ? 6 : (d.getDay()-1);
} | javascript | {
"resource": ""
} | |
q24523 | train | function(d) {
"use strict";
if (typeof d === "number") {
d = new Date(d);
}
return new Date(d.getFullYear(), d.getMonth()+1, 0);
} | javascript | {
"resource": ""
} | |
q24524 | train | function (d, range) {
"use strict";
var start = new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours());
var stop = null;
if (range instanceof Date) {
stop = new Date(range.getFullYear(), range.getMonth(), range.getDate(), range.getHours());
} else {
stop = new Date(start);
stop.setHours(stop.getHours() + range);
}
var domains = d3.time.hours(Math.min(start, stop), Math.max(start, stop));
// Passing from DST to standard time
// If there are 25 hours, let's compress the duplicate hours
var i = 0;
var total = domains.length;
for(i = 0; i < total; i++) {
if (i > 0 && (domains[i].getHours() === domains[i-1].getHours())) {
this.DSTDomain.push(domains[i].getTime());
domains.splice(i, 1);
break;
}
}
// d3.time.hours is returning more hours than needed when changing
// from DST to standard time, because there is really 2 hours between
// 1am and 2am!
if (typeof range === "number" && domains.length > Math.abs(range)) {
domains.splice(domains.length-1, 1);
}
return domains;
} | javascript | {
"resource": ""
} | |
q24525 | train | function (d, range) {
"use strict";
var start = new Date(d.getFullYear(), d.getMonth(), d.getDate());
var stop = null;
if (range instanceof Date) {
stop = new Date(range.getFullYear(), range.getMonth(), range.getDate());
} else {
stop = new Date(start);
stop = new Date(stop.setDate(stop.getDate() + parseInt(range, 10)));
}
return d3.time.days(Math.min(start, stop), Math.max(start, stop));
} | javascript | {
"resource": ""
} | |
q24526 | train | function (d, range) {
"use strict";
var weekStart;
if (this.options.weekStartOnMonday === false) {
weekStart = new Date(d.getFullYear(), d.getMonth(), d.getDate() - d.getDay());
} else {
if (d.getDay() === 1) {
weekStart = new Date(d.getFullYear(), d.getMonth(), d.getDate());
} else if (d.getDay() === 0) {
weekStart = new Date(d.getFullYear(), d.getMonth(), d.getDate());
weekStart.setDate(weekStart.getDate() - 6);
} else {
weekStart = new Date(d.getFullYear(), d.getMonth(), d.getDate()-d.getDay()+1);
}
}
var endDate = new Date(weekStart);
var stop = range;
if (typeof range !== "object") {
stop = new Date(endDate.setDate(endDate.getDate() + range * 7));
}
return (this.options.weekStartOnMonday === true) ?
d3.time.mondays(Math.min(weekStart, stop), Math.max(weekStart, stop)):
d3.time.sundays(Math.min(weekStart, stop), Math.max(weekStart, stop))
;
} | javascript | {
"resource": ""
} | |
q24527 | train | function (d, range) {
"use strict";
var start = new Date(d.getFullYear(), d.getMonth());
var stop = null;
if (range instanceof Date) {
stop = new Date(range.getFullYear(), range.getMonth());
} else {
stop = new Date(start);
stop = stop.setMonth(stop.getMonth()+range);
}
return d3.time.months(Math.min(start, stop), Math.max(start, stop));
} | javascript | {
"resource": ""
} | |
q24528 | train | function(d, range){
"use strict";
var start = new Date(d.getFullYear(), 0);
var stop = null;
if (range instanceof Date) {
stop = new Date(range.getFullYear(), 0);
} else {
stop = new Date(d.getFullYear()+range, 0);
}
return d3.time.years(Math.min(start, stop), Math.max(start, stop));
} | javascript | {
"resource": ""
} | |
q24529 | train | function(date, range) {
"use strict";
if (typeof date === "number") {
date = new Date(date);
}
if (arguments.length < 2) {
range = this.options.range;
}
switch(this.options.domain) {
case "hour" :
var domains = this.getHourDomain(date, range);
// Case where an hour is missing, when passing from standard time to DST
// Missing hour is perfectly acceptabl in subDomain, but not in domains
if (typeof range === "number" && domains.length < range) {
if (range > 0) {
domains.push(this.getHourDomain(domains[domains.length-1], 2)[1]);
} else {
domains.shift(this.getHourDomain(domains[0], -2)[0]);
}
}
return domains;
case "day" :
return this.getDayDomain(date, range);
case "week" :
return this.getWeekDomain(date, range);
case "month":
return this.getMonthDomain(date, range);
case "year" :
return this.getYearDomain(date, range);
}
} | javascript | {
"resource": ""
} | |
q24530 | train | function(data, updateMode, startDate, endDate) {
"use strict";
if (updateMode === this.RESET_ALL_ON_UPDATE) {
this._domains.forEach(function(key, value) {
value.forEach(function(element, index, array) {
array[index].v = null;
});
});
}
var temp = {};
var extractTime = function(d) { return d.t; };
/*jshint forin:false */
for (var d in data) {
var date = new Date(d*1000);
var domainUnit = this.getDomain(date)[0].getTime();
// The current data belongs to a domain that was compressed
// Compress the data for the two duplicate hours into the same hour
if (this.DSTDomain.indexOf(domainUnit) >= 0) {
// Re-assign all data to the first or the second duplicate hours
// depending on which is visible
if (this._domains.has(domainUnit - 3600 * 1000)) {
domainUnit -= 3600 * 1000;
}
}
// Skip if data is not relevant to current domain
if (isNaN(d) || !data.hasOwnProperty(d) || !this._domains.has(domainUnit) || !(domainUnit >= +startDate && domainUnit < +endDate)) {
continue;
}
var subDomainsData = this._domains.get(domainUnit);
if (!temp.hasOwnProperty(domainUnit)) {
temp[domainUnit] = subDomainsData.map(extractTime);
}
var index = temp[domainUnit].indexOf(this._domainType[this.options.subDomain].extractUnit(date));
if (updateMode === this.RESET_SINGLE_ON_UPDATE) {
subDomainsData[index].v = data[d];
} else {
if (!isNaN(subDomainsData[index].v)) {
subDomainsData[index].v += data[d];
} else {
subDomainsData[index].v = data[d];
}
}
}
} | javascript | {
"resource": ""
} | |
q24531 | train | function() {
"use strict";
var parent = this;
var options = parent.options;
var legendWidth = options.displayLegend ? (parent.Legend.getDim("width") + options.legendMargin[1] + options.legendMargin[3]) : 0;
var legendHeight = options.displayLegend ? (parent.Legend.getDim("height") + options.legendMargin[0] + options.legendMargin[2]) : 0;
var graphWidth = parent.graphDim.width - options.domainGutter - options.cellPadding;
var graphHeight = parent.graphDim.height - options.domainGutter - options.cellPadding;
this.root.transition().duration(options.animationDuration)
.attr("width", function() {
if (options.legendVerticalPosition === "middle" || options.legendVerticalPosition === "center") {
return graphWidth + legendWidth;
}
return Math.max(graphWidth, legendWidth);
})
.attr("height", function() {
if (options.legendVerticalPosition === "middle" || options.legendVerticalPosition === "center") {
return Math.max(graphHeight, legendHeight);
}
return graphHeight + legendHeight;
})
;
this.root.select(".graph").transition().duration(options.animationDuration)
.attr("y", function() {
if (options.legendVerticalPosition === "top") {
return legendHeight;
}
return 0;
})
.attr("x", function() {
if (
(options.legendVerticalPosition === "middle" || options.legendVerticalPosition === "center") &&
options.legendHorizontalPosition === "left") {
return legendWidth;
}
return 0;
})
;
} | javascript | {
"resource": ""
} | |
q24532 | train | function(date, reset) {
"use strict";
if (arguments.length < 2) {
reset = false;
}
var domains = this.getDomainKeys();
var firstDomain = domains[0];
var lastDomain = domains[domains.length-1];
if (date < firstDomain) {
return this.loadPreviousDomain(this.getDomain(firstDomain, date).length);
} else {
if (reset) {
return this.loadNextDomain(this.getDomain(firstDomain, date).length);
}
if (date > lastDomain) {
return this.loadNextDomain(this.getDomain(lastDomain, date).length);
}
}
return false;
} | javascript | {
"resource": ""
} | |
q24533 | train | function(dataSource, afterLoad, updateMode) {
"use strict";
if (arguments.length === 0) {
dataSource = this.options.data;
}
if (arguments.length < 2) {
afterLoad = true;
}
if (arguments.length < 3) {
updateMode = this.RESET_ALL_ON_UPDATE;
}
var domains = this.getDomainKeys();
var self = this;
this.getDatas(
dataSource,
new Date(domains[0]),
this.getSubDomain(domains[domains.length-1]).pop(),
function() {
self.fill();
self.afterUpdate();
},
afterLoad,
updateMode
);
} | javascript | {
"resource": ""
} | |
q24534 | train | function(callback) {
"use strict";
this.root.transition().duration(this.options.animationDuration)
.attr("width", 0)
.attr("height", 0)
.remove()
.each("end", function() {
if (typeof callback === "function") {
callback();
} else if (typeof callback !== "undefined") {
console.log("Provided callback for destroy() is not a function.");
}
})
;
return null;
} | javascript | {
"resource": ""
} | |
q24535 | arrayEquals | train | function arrayEquals(arrayA, arrayB) {
"use strict";
// if the other array is a falsy value, return
if (!arrayB || !arrayA) {
return false;
}
// compare lengths - can save a lot of time
if (arrayA.length !== arrayB.length) {
return false;
}
for (var i = 0; i < arrayA.length; i++) {
// Check if we have nested arrays
if (arrayA[i] instanceof Array && arrayB[i] instanceof Array) {
// recurse into the nested arrays
if (!arrayEquals(arrayA[i], arrayB[i])) {
return false;
}
}
else if (arrayA[i] !== arrayB[i]) {
// Warning - two different object instances will never be equal: {x:20} != {x:20}
return false;
}
}
return true;
} | javascript | {
"resource": ""
} |
q24536 | loadSavedState | train | function loadSavedState () {
var output;
try {
output = jsonfile.readFileSync(STATE_FILE);
} catch (ex) {
winston.info('No previous state found, continuing');
output = {
subscriptions: [],
callback: '',
history: {},
version: '0.0.0'
};
}
return output;
} | javascript | {
"resource": ""
} |
q24537 | saveState | train | function saveState () {
winston.info('Saving current state');
jsonfile.writeFileSync(STATE_FILE, {
subscriptions: subscriptions,
callback: callback,
history: history,
version: CURRENT_VERSION
}, {
spaces: 4
});
} | javascript | {
"resource": ""
} |
q24538 | migrateState | train | function migrateState (version) {
// Make sure the object exists
if (!config.mqtt) {
config.mqtt = {};
}
// This is the previous default, but it's totally wrong
if (!config.mqtt.preface) {
config.mqtt.preface = '/smartthings';
}
// Default Suffixes
if (!config.mqtt[SUFFIX_READ_STATE]) {
config.mqtt[SUFFIX_READ_STATE] = '';
}
if (!config.mqtt[SUFFIX_COMMAND]) {
config.mqtt[SUFFIX_COMMAND] = '';
}
if (!config.mqtt[SUFFIX_WRITE_STATE]) {
config.mqtt[SUFFIX_WRITE_STATE] = '';
}
// Default retain
if (config.mqtt[RETAIN] !== false) {
config.mqtt[RETAIN] = true;
}
// Default port
if (!config.port) {
config.port = 8080;
}
// Default protocol
if (!url.parse(config.mqtt.host).protocol) {
config.mqtt.host = 'mqtt://' + config.mqtt.host;
}
// Stuff was previously in subscription.json, load that and migrate it
var SUBSCRIPTION_FILE = path.join(CONFIG_DIR, 'subscription.json');
if (semver.lt(version, '1.1.0') && fs.existsSync(SUBSCRIPTION_FILE)) {
var oldState = jsonfile.readFileSync(SUBSCRIPTION_FILE);
callback = oldState.callback;
subscriptions = oldState.topics;
}
saveState();
} | javascript | {
"resource": ""
} |
q24539 | handleSubscribeEvent | train | function handleSubscribeEvent (req, res) {
// Subscribe to all events
subscriptions = [];
Object.keys(req.body.devices).forEach(function (property) {
req.body.devices[property].forEach(function (device) {
subscriptions.push(getTopicFor(device, property, TOPIC_COMMAND));
subscriptions.push(getTopicFor(device, property, TOPIC_WRITE_STATE));
});
});
// Store callback
callback = req.body.callback;
// Store current state on disk
saveState();
// Subscribe to events
winston.info('Subscribing to ' + subscriptions.join(', '));
client.subscribe(subscriptions, function () {
res.send({
status: 'OK'
});
});
} | javascript | {
"resource": ""
} |
q24540 | getTopicFor | train | function getTopicFor (device, property, type) {
var tree = [config.mqtt.preface, device, property],
suffix;
if (type === TOPIC_COMMAND) {
suffix = config.mqtt[SUFFIX_COMMAND];
} else if (type === TOPIC_READ_STATE) {
suffix = config.mqtt[SUFFIX_READ_STATE];
} else if (type === TOPIC_WRITE_STATE) {
suffix = config.mqtt[SUFFIX_WRITE_STATE];
}
if (suffix) {
tree.push(suffix);
}
return tree.join('/');
} | javascript | {
"resource": ""
} |
q24541 | parseMQTTMessage | train | function parseMQTTMessage (topic, message) {
var contents = message.toString();
winston.info('Incoming message from MQTT: %s = %s', topic, contents);
// Remove the preface from the topic before splitting it
var pieces = topic.substr(config.mqtt.preface.length + 1).split('/'),
device = pieces[0],
property = pieces[1],
topicReadState = getTopicFor(device, property, TOPIC_READ_STATE),
topicWriteState = getTopicFor(device, property, TOPIC_WRITE_STATE),
topicSwitchState = getTopicFor(device, 'switch', TOPIC_READ_STATE),
topicLevelCommand = getTopicFor(device, 'level', TOPIC_COMMAND);
// Deduplicate only if the incoming message topic is the same as the read state topic
if (topic === topicReadState) {
if (history[topic] === contents) {
winston.info('Skipping duplicate message from: %s = %s', topic, contents);
return;
}
}
history[topic] = contents;
// If sending level data and the switch is off, don't send anything
// SmartThings will turn the device on (which is confusing)
if (property === 'level' && history[topicSwitchState] === 'off') {
winston.info('Skipping level set due to device being off');
return;
}
// If sending switch data and there is already a nonzero level value, send level instead
// SmartThings will turn the device on
if (property === 'switch' && contents === 'on' &&
history[topicLevelCommand] > 0) {
winston.info('Passing level instead of switch on');
property = 'level';
contents = history[topicLevelCommand];
}
request.post({
url: 'http://' + callback,
json: {
name: device,
type: property,
value: contents,
command: (!pieces[2] || pieces[2] && pieces[2] === config.mqtt[SUFFIX_COMMAND])
}
}, function (error, resp) {
if (error) {
// @TODO handle the response from SmartThings
winston.error('Error from SmartThings Hub: %s', error.toString());
winston.error(JSON.stringify(error, null, 4));
winston.error(JSON.stringify(resp, null, 4));
}
});
} | javascript | {
"resource": ""
} |
q24542 | build | train | function build() {
module.el.find('.ple-module-content').append('<div style="display:none;" class="ple-title-related"></div>');
relatedEl = module.el.find('.ple-title-related');
relatedEl.append('<p class="ple-help">Does your work relate to one of these? Click to alert those contributors.</p><hr style="margin: 4px 0;" />');
} | javascript | {
"resource": ""
} |
q24543 | train | function() {
var _formatter = this;
// functions that accept standard <data> and output form data for known services
_formatter.schemas = {
"publiclab": function(data) {
var output = {};
output.title = data.title || null;
output.body = data.body || null;
// we can remove this from server req, since we're authenticated
output.authenticity_token = data.token || null;
// Whether note will be draft or not
output.draft = data.draft || false;
// Optional:
output.tags = data.tags || null; // comma delimited
output.has_main_image = data.has_main_image || null;
output.main_image = data.main_image || null; // id to associate with pre-uploaded image
output.node_images = data.node_images || null; // comma-separated image.ids, I think
// photo is probably actually a multipart, but we pre-upload anyways, so probably not necessary:
output.image = { };
output.image.photo = data.image || null;
return output;
}//,
// "drupal": {
// "title": null,
// "body": null
// }
}
_formatter.convert = function(data, destination) {
// return formatted version of data
return _formatter.schemas[destination](data);
}
} | javascript | {
"resource": ""
} | |
q24544 | train | function(options) {
var self = this
options = options || {}
if (typeof options === 'function') throw new Error('then!')
return self
.validate()
.then(function() {
return self._create_or_update(options)
})
.then(function() {
// eliminate changes -> we just saved it to the database!
self.changes = {}
})
.then(function() {
return self
})
} | javascript | {
"resource": ""
} | |
q24545 | train | function(allowedAttributes, exportObject) {
var definition = this.definition
var tmp = exportObject || definition.store.utils.clone(this.attributes)
for (var i in definition.relations) {
var relation = definition.relations[i]
if (this['_' + relation.name]) {
tmp[relation.name] = this['_' + relation.name]
if (typeof tmp[relation.name].toJson === 'function')
tmp[relation.name] = tmp[relation.name].toJson()
}
}
if (!allowedAttributes && this.allowedAttributes)
allowedAttributes = this.allowedAttributes
for (var name in tmp) {
if (allowedAttributes && allowedAttributes.indexOf(name) === -1) {
delete tmp[name]
} else {
if (
definition.attributes &&
definition.attributes[name] &&
definition.attributes[name].hidden !== true
) {
tmp[name] = definition.cast(name, tmp[name], 'output', this)
if (tmp[name] && typeof tmp[name].toJson === 'function'){
tmp[name] = tmp[name].toJson()
}
// convert to external names
var value = tmp[name]
delete tmp[name]
tmp[definition.attributes[name].name] = value
}
}
}
return tmp
} | javascript | {
"resource": ""
} | |
q24546 | train | function(allowedAttributes) {
var tmp = []
this.forEach(function(record) {
tmp.push(record.toJson(allowedAttributes))
})
return tmp
} | javascript | {
"resource": ""
} | |
q24547 | train | function(name, fn, lazy) {
const Utils = this.store.utils
if (!fn && this.model) fn = this.model[name]
if (!fn)
throw new Error('You need to provide a function in order to use a scope')
var tmp = function() {
var args = Utils.args(arguments)
const self = this.chain()._unresolve() // if the collection is already resolved, return a unresolved and empty copy!
if (lazy) {
self.addInternal('active_scopes', function() {
return fn.apply(this, args)
})
} else {
fn.apply(self, args)
}
return self
}
this.staticMethods[name] = tmp
return this
} | javascript | {
"resource": ""
} | |
q24548 | train | function(options) {
options = options || {}
if (this.chained && options.clone !== true) return this
var ChainModel = new this.definition.ChainGenerator(options)
if (this.chained && options.clone === true) {
ChainModel._internal_attributes = this.definition.store.utils.clone(
this._internal_attributes,
options.exclude
)
ChainModel._internal_attributes.cloned_relation_to = ChainModel._internal_attributes.relation_to
ChainModel.clearInternal('relation_to')
}
return ChainModel.callDefaultScopes()
} | javascript | {
"resource": ""
} | |
q24549 | train | function() {
var self = this
Object.keys(this.definition.relations).forEach(function(key) {
delete self.relations[key]
})
return this
} | javascript | {
"resource": ""
} | |
q24550 | train | function(name, type, options) {
const Store = require('../store')
options = options || {}
type = type || String
if (typeof type === 'string') {
type = type.toLowerCase()
}
var fieldType = this.store.getType(type)
if (!fieldType) {
throw new Store.UnknownAttributeTypeError(type)
}
Object.assign(options, fieldType.defaults)
options.name = this.store.toExternalAttributeName(name)
options.type = fieldType
options.writable =
options.writable === undefined ? true : !!options.writable
options.readable =
options.readable === undefined ? true : !!options.readable
options.track_object_changes =
options.track_object_changes === undefined
? false
: !!options.track_object_changes
options.notifications = []
this.attributes[name] = options
this.setter(
name,
options.setter ||
function(value) {
this.set(options.name, value)
}
)
if (options.readable || options.getter) {
this.getter(
name,
options.getter ||
function() {
return this.get(name)
},
true
)
}
return this
} | javascript | {
"resource": ""
} | |
q24551 | train | function(name, fn) {
const externalName = this.store.toExternalAttributeName(name)
this.instanceMethods.__defineSetter__(name, fn)
if(externalName !== name) this.instanceMethods.__defineSetter__(externalName, fn)
return this
} | javascript | {
"resource": ""
} | |
q24552 | train | function(name, fn) {
const _name = this.store.toInternalAttributeName(name)
const Store = require('../store')
if (!this.attributes[_name]) throw new Store.UnknownAttributeError(name)
this.attributes[_name].variant = fn
this[name + '$'] = function(args) {
return fn.call(this, this[_name], args)
}
return this
} | javascript | {
"resource": ""
} | |
q24553 | train | function(name, value) {
if (!name && !value) return
var values = name
var castType = value
var singleAssign = false
if (typeof name === 'string') {
values = {}
values[name] = value
castType = 'input'
singleAssign = true
}
for (var field in this.definition.attributes) {
if (this.definition.attributes.hasOwnProperty(field)) {
var definition = this.definition.attributes[field]
var fieldName = castType === 'input' ? definition.name : field
if (singleAssign && values[fieldName] === undefined) {
continue
}
value = values[fieldName]
if (!singleAssign && value && typeof definition.setter === 'function') {
definition.setter.call(this, value)
continue
}
if (
value === undefined &&
this.attributes[field] === undefined &&
definition.default !== undefined
) {
if (typeof definition.default === 'function')
value = definition.default()
else value = this.definition.store.utils.clone(definition.default)
}
if (value === undefined && this.attributes[field] !== undefined) {
value = this.attributes[field]
}
if (value === undefined) {
value = null
}
// typecasted value
castType = castType || 'input'
if (!definition.type.cast[castType]) {
castType = 'input'
}
value =
value !== null
? this.definition.cast(field, value, castType, this)
: null
if (this.attributes[field] !== value) {
if (value && typeof value === 'object') {
// automatically set object tracking to true if the value is still an object after the casting
definition.track_object_changes = true
}
if (
definition.writable &&
!(value === null && this.attributes[field] === undefined)
) {
var beforeValue = this[field]
var afterValue = value
if (this.changes[field]) {
this.changes[field][1] = afterValue
} else {
this.changes[field] = [beforeValue, afterValue]
}
}
if (
definition.track_object_changes &&
(this.object_changes[field] === undefined || castType !== 'input')
) {
// initial object hash
this.object_changes[field] = [
this.definition.store.utils.getHash(value),
JSON.stringify(value)
]
}
if (definition.notifications) {
definition.notifications.forEach(function(fn) {
fn.call(this, value, castType)
}, this)
}
this.attributes[field] = value
// TODO: remove in 2.1!
if (definition.emit_events && beforeValue !== value) {
// emit old_value, new_value
this.definition.emit(field + '_changed', this, beforeValue, value)
}
}
}
}
return this
} | javascript | {
"resource": ""
} | |
q24554 | train | function(name) {
var attr = this.definition.attributes[name]
if (attr) {
// set undefined values to null
if (this.attributes[name] === undefined) {
this.attributes[name] = null
}
return this.definition.cast(name, this.attributes[name], 'output', this)
}
return null
} | javascript | {
"resource": ""
} | |
q24555 | train | function() {
this.checkObjectChanges()
var tmp = {}
for (var name in this.changes) {
if (this.changes.hasOwnProperty(name)) {
if (
!this.allowed_attributes ||
(this.allowed_attributes &&
this.allowed_attributes.indexOf(name) !== -1)
) {
tmp[name] = this.changes[name]
}
}
}
return tmp
} | javascript | {
"resource": ""
} | |
q24556 | train | function() {
for (var name in this.changes) {
if (this.changes.hasOwnProperty(name)) {
this.attributes[name] = this.changes[name][0]
}
}
this.changes = {}
return this
} | javascript | {
"resource": ""
} | |
q24557 | train | function() {
const Utils = this.definition.store.utils
const self = this.chain()._unresolve() // if the collection is already resolved, return a unresolved and empty copy!
const existingConditions = self.getInternal('conditions') || []
const existingMap = {}
existingConditions.forEach(function(cond) {
const key =
cond.type +
'|' +
cond.attribute +
'|' +
cond.operator +
'|' +
JSON.stringify(cond.value)
existingMap[key] = true
})
var attributeNames = Object.keys(self.definition.attributes)
attributeNames = attributeNames.concat(attributeNames.map(function(name){
return self.definition.attributes[name].name
}))
const parentRelations = self.getInternal('parent_relations')
const conditions = Utils.toConditionList(
Utils.args(arguments),
attributeNames
)
conditions.forEach(function(cond) {
if (
cond.type === 'relation' &&
!self.definition.relations[cond.relation] &&
!self.options.polymorph
) {
throw new Error(
'Can\'t find attribute or relation "' +
cond.relation +
'" for ' +
self.definition.modelName
)
}
// used for joins only
if (parentRelations) {
cond.parents = parentRelations
if (cond.value && cond.value.$attribute && !cond.value.$parents) {
cond.value.$parents = parentRelations
}
}
if(cond.attribute) cond.attribute = self.store.toInternalAttributeName(cond.attribute)
const key =
cond.type +
'|' +
cond.attribute +
'|' +
cond.operator +
'|' +
JSON.stringify(cond.value)
if (existingMap[key] && cond.type !== 'raw') return
self.addInternal('conditions', cond)
})
return self
} | javascript | {
"resource": ""
} | |
q24558 | train | function(resolve) {
var self = this.chain()
// if .find(null) was called
if (self.getInternal('exec_null')) {
return Promise.resolve(null)
}
var relation = self.getInternal('relation')
if (relation && typeof relation.loadWithCollection === 'function') {
const promise = relation.loadWithCollection(self)
if (promise && promise.then) return promise.then(resolve)
}
var dataLoaded = self.getInternal('data_loaded')
var options = self.getExecOptions()
var data = {}
if (dataLoaded) data.result = dataLoaded
return self
.callInterceptors('beforeFind', [options])
.then(function() {
return self.callInterceptors('onFind', [options, data], {
executeInParallel: true
})
})
.then(function() {
return self.callInterceptors('afterFind', [data])
})
.then(function() {
if (typeof resolve === 'function') return resolve(data.result)
return data.result
})
} | javascript | {
"resource": ""
} | |
q24559 | train | function() {
var self = this
var validations = []
return self
.callInterceptors('beforeValidation', [self])
.then(function() {
for (var field in self.definition.validations) {
var fieldValidations = self.definition.validations[field]
// set the scope of all validator function to the current record
for (var i in fieldValidations) {
validations.push(fieldValidations[i].bind(self))
}
}
return self.store.utils.parallel(validations)
})
.then(function(result) {
if (self.errors.has) throw self.errors
})
.then(function() {
return self.callInterceptors('afterValidation', [self])
})
.then(function() {
return self
})
} | javascript | {
"resource": ""
} | |
q24560 | train | function(resolve) {
var self = this
return this.validate()
.then(function() {
return true
})
.catch(function(error) {
if (error instanceof self.store.ValidationError) return false
throw error
})
.then(resolve)
} | javascript | {
"resource": ""
} | |
q24561 | train | function(options) {
const Store = require('../../store')
var self = this
var primaryKeys = this.definition.primaryKeys
var condition = {}
options = options || {}
for (var i = 0; i < primaryKeys.length; i++) {
condition[primaryKeys[i]] = this[primaryKeys[i]]
}
return self.store.startTransaction(options, function() {
return self
.callInterceptors('beforeDestroy', [self, options])
.then(function() {
var query = self.definition.query(options)
return query
.where(condition)
.delete()
.catch(function(error) {
debug(query.toString())
throw new Store.SQLError(error)
})
.then(function() {
debug(query.toString())
})
.then(function() {
return self.callInterceptors('afterDestroy', [self, options])
})
.then(function() {
self.__exists = false
return self
})
})
})
} | javascript | {
"resource": ""
} | |
q24562 | train | function(data, options) {
var self = this
if (Array.isArray(data)) {
return this.chain()
.add(data)
.save()
}
return this.runScopes().then(function() {
return self.new(data).save(options)
})
} | javascript | {
"resource": ""
} | |
q24563 | train | function(index) {
var self = this.chain()
if (typeof index !== 'number') {
index = self.indexOf(index)
}
const record = self[index]
var relation = self.getInternal('relation')
var parentRecord = self.getInternal('relation_to')
if (
record &&
relation &&
parentRecord &&
typeof relation.remove === 'function'
) {
relation.remove.call(self, parentRecord, record)
}
self.splice(index, 1)
return self
} | javascript | {
"resource": ""
} | |
q24564 | save | train | function save(options) {
const self = this
options = options || {}
if (self.options.polymorph) return this.callParent(options)
return Promise.all(
this.map(function(record) {
// validate all records at once.
return record.validate()
})
)
.then(function() {
// if validation succeeded, start the transaction
return self.store.startTransaction(options, function() {
return self
._runLazyOperation(options)
.then(function() {
// inside the transaction create all new records and afterwards save all the others
return self._create(options)
})
.then(function() {
// will save all existing records with changes...
return self.callParent(options, save)
})
})
})
.then(function() {
return self
})
} | javascript | {
"resource": ""
} |
q24565 | train | function(store, modelName) {
this.store = store
this.modelName = modelName
this.model = null
this.middleware = []
this.instanceMethods = {}
this.staticMethods = {}
events.EventEmitter.call(this)
} | javascript | {
"resource": ""
} | |
q24566 | nextAnim | train | function nextAnim() {
const anim = config.animations[++index];
if (anim) {
const encoder = new GIFEncoder(app.view.width, app.view.height);
// Stream output
encoder.createReadStream().pipe(fs.createWriteStream(
path.join(outputPath, anim.filename + '.gif')
));
encoder.start();
encoder.setRepeat(0); // 0 for repeat, -1 for no-repeat
encoder.setDelay(anim.delay || 500); // frame delay in ms
encoder.setQuality(10); // image quality. 10 is default.
// Add the frames
anim.frames.forEach((frame) => {
encoder.addFrame(frames[frame]);
delete frames[frame];
});
encoder.finish();
// Wait for next stack to render next animation
setTimeout(nextAnim, 0);
}
else {
complete();
}
} | javascript | {
"resource": ""
} |
q24567 | dedupeDefaultVert | train | function dedupeDefaultVert() {
const defaultVert = path.join(__dirname, 'tools/fragments/default.vert');
const fragment = fs.readFileSync(defaultVert, 'utf8')
.replace(/\n/g, '\\\\n')
.replace(/([()*=.])/g, '\\$1');
const pattern = new RegExp(`(var ([^=\\s]+)\\s?=\\s?)"${fragment}"`, 'g');
return {
name: 'dedupeDefaultVert',
renderChunk(code) {
const matches = [];
let match;
while ((match = pattern.exec(code)) !== null) {
matches.push(match);
}
if (matches.length <= 1) {
return null;
}
const str = new MagicString(code);
const key = matches[0][2];
for (let i = 1; i < matches.length; i++) {
const match = matches[i];
const start = code.indexOf(match[0]);
str.overwrite(
start,
start + match[0].length,
match[1] + key
);
}
return {
code: str.toString(),
map: str.generateMap({ hires: true }),
};
},
};
} | javascript | {
"resource": ""
} |
q24568 | getSortedPackages | train | async function getSortedPackages() {
// Support --scope and --ignore globs
const {scope, ignore} = minimist(process.argv.slice(2));
// Standard Lerna plumbing getting packages
const packages = await getPackages(__dirname);
const filtered = filterPackages(
packages,
scope,
ignore,
false
);
return batchPackages(filtered)
.reduce((arr, batch) => arr.concat(batch), []);
} | javascript | {
"resource": ""
} |
q24569 | Agent | train | function Agent(family, major, minor, patch, source) {
this.family = family || 'Other';
this.major = major || '0';
this.minor = minor || '0';
this.patch = patch || '0';
this.source = source || '';
} | javascript | {
"resource": ""
} |
q24570 | set | train | function set(os) {
if (!(os instanceof OperatingSystem)) return false;
return Object.defineProperty(this, 'os', {
value: os
}).os;
} | javascript | {
"resource": ""
} |
q24571 | set | train | function set(device) {
if (!(device instanceof Device)) return false;
return Object.defineProperty(this, 'device', {
value: device
}).device;
} | javascript | {
"resource": ""
} |
q24572 | OperatingSystem | train | function OperatingSystem(family, major, minor, patch) {
this.family = family || 'Other';
this.major = major || '0';
this.minor = minor || '0';
this.patch = patch || '0';
} | javascript | {
"resource": ""
} |
q24573 | Device | train | function Device(family, major, minor, patch) {
this.family = family || 'Other';
this.major = major || '0';
this.minor = minor || '0';
this.patch = patch || '0';
} | javascript | {
"resource": ""
} |
q24574 | isSafe | train | function isSafe(userAgent) {
var consecutive = 0
, code = 0;
if (userAgent.length > 1000) return false;
for (var i = 0; i < userAgent.length; i++) {
code = userAgent.charCodeAt(i);
// numbers between 0 and 9, letters between a and z, spaces and control
if ((code >= 48 && code <= 57) || (code >= 97 && code <= 122) || code <= 32) {
consecutive++;
} else {
consecutive = 0;
}
if (consecutive >= 100) {
return false;
}
}
return true
} | javascript | {
"resource": ""
} |
q24575 | setAWSWhitelist | train | function setAWSWhitelist(source) {
if (!source || source instanceof String || !(typeof source === 'string' || (source instanceof Object)))
throw new Error('Please specify a path to the local whitelist file, or supply a whitelist source object.');
capturer = new CallCapturer(source);
} | javascript | {
"resource": ""
} |
q24576 | appendAWSWhitelist | train | function appendAWSWhitelist(source) {
if (!source || source instanceof String || !(typeof source === 'string' || (source instanceof Object)))
throw new Error('Please specify a path to the local whitelist file, or supply a whitelist source object.');
capturer.append(source);
} | javascript | {
"resource": ""
} |
q24577 | batchSendData | train | function batchSendData (ops, callback) {
var client = dgram.createSocket('udp4');
executeSendData(client, ops, 0, function () {
try {
client.close();
} finally {
callback();
}
});
} | javascript | {
"resource": ""
} |
q24578 | executeSendData | train | function executeSendData (client, ops, index, callback) {
if (index >= ops.length) {
callback();
return;
}
sendMessage(client, ops[index], function () {
executeSendData(client, ops, index+1, callback);
});
} | javascript | {
"resource": ""
} |
q24579 | sendMessage | train | function sendMessage (client, data, batchCallback) {
var msg = data.msg;
var offset = data.offset;
var length = data.length;
var port = data.port;
var address = data.address;
var callback = data.callback;
client.send(msg, offset, length, port, address, function(err) {
try {
callback(err);
} finally {
batchCallback();
}
});
} | javascript | {
"resource": ""
} |
q24580 | send | train | function send(segment) {
var client = this.socket;
var formatted = segment.format();
var data = PROTOCOL_HEADER + PROTOCOL_DELIMITER + formatted;
var message = new Buffer(data);
var short = '{"trace_id:"' + segment.trace_id + '","id":"' + segment.id + '"}';
var type = segment.type === 'subsegment' ? 'Subsegment' : 'Segment';
client.send(message, 0, message.length, this.daemonConfig.udp_port, this.daemonConfig.udp_ip, function(err) {
if (err) {
if (err.code === 'EMSGSIZE')
logger.getLogger().error(type + ' too large to send: ' + short + ' (' + message.length + ' bytes).');
else
logger.getLogger().error('Error occured sending segment: ', err);
} else {
logger.getLogger().debug(type + ' sent: {"trace_id:"' + segment.trace_id + '","id":"' + segment.id + '"}');
logger.getLogger().debug('UDP message sent: ' + segment);
}
});
} | javascript | {
"resource": ""
} |
q24581 | captureAWS | train | function captureAWS(awssdk) {
if (!semver.gte(awssdk.VERSION, minVersion))
throw new Error ('AWS SDK version ' + minVersion + ' or greater required.');
for (var prop in awssdk) {
if (awssdk[prop].serviceIdentifier) {
var Service = awssdk[prop];
Service.prototype.customizeRequests(captureAWSRequest);
}
}
return awssdk;
} | javascript | {
"resource": ""
} |
q24582 | SqlData | train | function SqlData(databaseVer, driverVer, user, url, queryType) {
this.init(databaseVer, driverVer, user, url, queryType);
} | javascript | {
"resource": ""
} |
q24583 | captureFunc | train | function captureFunc(name, fcn, parent) {
validate(name, fcn);
var current, executeFcn;
var parentSeg = contextUtils.resolveSegment(parent);
if (!parentSeg) {
logger.getLogger().warn('Failed to capture function.');
return fcn();
}
current = parentSeg.addNewSubsegment(name);
executeFcn = captureFcn(fcn, current);
try {
executeFcn(current);
current.close();
} catch (e) {
current.close(e);
throw(e);
}
} | javascript | {
"resource": ""
} |
q24584 | SamplingRule | train | function SamplingRule(name, priority, rate, reservoirSize,
host, httpMethod, urlPath, serviceName, serviceType) {
this.init(name, priority, rate, reservoirSize,
host, httpMethod, urlPath, serviceName, serviceType);
} | javascript | {
"resource": ""
} |
q24585 | train | function(plugins) {
var pluginData = {};
plugins.forEach(function(plugin) {
plugin.getData(function(data) {
if (data) {
for (var attribute in data) { pluginData[attribute] = data[attribute]; }
}
});
segmentUtils.setOrigin(plugin.originName);
segmentUtils.setPluginData(pluginData);
});
} | javascript | {
"resource": ""
} | |
q24586 | Message | train | function Message(stanClient, msg, subscription) {
this.stanClient = stanClient;
this.msg = msg;
this.subscription = subscription;
} | javascript | {
"resource": ""
} |
q24587 | runTransient | train | function runTransient() {
var c = document.createElement('canvas');
var gl = c.getContext('webgl');
var ext = gl.getExtension('WEBGL_debug_renderer_info');
var renderer = gl.getParameter(ext.UNMASKED_RENDERER_WEBGL);
console.log(renderer);
} | javascript | {
"resource": ""
} |
q24588 | initWebGL | train | function initWebGL() {
gl = null;
try {
gl = canvas.getContext("experimental-webgl");
}
catch(e) {
alert(e);
}
// If we don't have a GL context, give up now
if (!gl) {
alert("Unable to initialize WebGL. Your browser may not support it.");
}
} | javascript | {
"resource": ""
} |
q24589 | getShader | train | function getShader(gl, source, isVertex) {
var shader = gl.createShader(isVertex ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
gl.shaderSource(shader, source);
gl.compileShader(shader);
// See if it compiled successfully
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert("An error occurred compiling the shaders: " + gl.getShaderInfoLog(shader));
return null;
}
return shader;
} | javascript | {
"resource": ""
} |
q24590 | train | function (arr, obj) {
if (!arr[obj[0]])
arr[obj[0]] = { normals: [], idx: [] };
var idx = arr[obj[0]].normals.indexOf(obj[1]);
return idx === -1 ? -1 : arr[obj[0]].idx[idx];
} | javascript | {
"resource": ""
} | |
q24591 | train | function (face, v) {
//Get the indices of triangles for each polygon
getTriangles(face, v);
//For each element in the triangles array.
//This var could contains 1 to an infinity of triangles
for (var k = 0; k < triangles.length; k++) {
// Set position indice
var indicePositionFromObj = parseInt(triangles[k]) - 1;
setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
positions[indicePositionFromObj], //Get the vectors data
BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
);
}
//Reset variable for the next line
triangles = [];
} | javascript | {
"resource": ""
} | |
q24592 | train | function (face, v) {
//Get the indices of triangles for each polygon
getTriangles(face, v);
for (var k = 0; k < triangles.length; k++) {
//triangle[k] = "1/1"
//Split the data for getting position and uv
var point = triangles[k].split("/"); // ["1", "1"]
//Set position indice
var indicePositionFromObj = parseInt(point[0]) - 1;
//Set uv indice
var indiceUvsFromObj = parseInt(point[1]) - 1;
setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
positions[indicePositionFromObj], //Get the values for each element
uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
);
}
//Reset variable for the next line
triangles = [];
} | javascript | {
"resource": ""
} | |
q24593 | train | function (face, v) {
//Get the indices of triangles for each polygon
getTriangles(face, v);
for (var k = 0; k < triangles.length; k++) {
//triangle[k] = "1/1/1"
//Split the data for getting position, uv, and normals
var point = triangles[k].split("/"); // ["1", "1", "1"]
// Set position indice
var indicePositionFromObj = parseInt(point[0]) - 1;
// Set uv indice
var indiceUvsFromObj = parseInt(point[1]) - 1;
// Set normal indice
var indiceNormalFromObj = parseInt(point[2]) - 1;
setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
);
}
//Reset variable for the next line
triangles = [];
} | javascript | {
"resource": ""
} | |
q24594 | train | function (face, v) {
getTriangles(face, v);
for (var k = 0; k < triangles.length; k++) {
//triangle[k] = "1//1"
//Split the data for getting position and normals
var point = triangles[k].split("//"); // ["1", "1"]
// We check indices, and normals
var indicePositionFromObj = parseInt(point[0]) - 1;
var indiceNormalFromObj = parseInt(point[1]) - 1;
setData(indicePositionFromObj, 1, //Default value for uv
indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
}
//Reset variable for the next line
triangles = [];
} | javascript | {
"resource": ""
} | |
q24595 | Color3 | train | function Color3(r, g, b) {
if (r === void 0) { r = 0; }
if (g === void 0) { g = 0; }
if (b === void 0) { b = 0; }
this.r = r;
this.g = g;
this.b = b;
} | javascript | {
"resource": ""
} |
q24596 | Quaternion | train | function Quaternion(x, y, z, w) {
if (x === void 0) { x = 0.0; }
if (y === void 0) { y = 0.0; }
if (z === void 0) { z = 0.0; }
if (w === void 0) { w = 1.0; }
this.x = x;
this.y = y;
this.z = z;
this.w = w;
} | javascript | {
"resource": ""
} |
q24597 | Path2 | train | function Path2(x, y) {
this._points = new Array();
this._length = 0.0;
this.closed = false;
this._points.push(new Vector2(x, y));
} | javascript | {
"resource": ""
} |
q24598 | getMergedStore | train | function getMergedStore(target) {
var classKey = target.getClassName();
if (__mergedStore[classKey]) {
return __mergedStore[classKey];
}
__mergedStore[classKey] = {};
var store = __mergedStore[classKey];
var currentTarget = target;
var currentKey = classKey;
while (currentKey) {
var initialStore = __decoratorInitialStore[currentKey];
for (var property in initialStore) {
store[property] = initialStore[property];
}
var parent_1 = void 0;
var done = false;
do {
parent_1 = Object.getPrototypeOf(currentTarget);
if (!parent_1.getClassName) {
done = true;
break;
}
if (parent_1.getClassName() !== currentKey) {
break;
}
currentTarget = parent_1;
} while (parent_1);
if (done) {
break;
}
currentKey = parent_1.getClassName();
currentTarget = parent_1;
}
return store;
} | javascript | {
"resource": ""
} |
q24599 | train | function () {
var boundingBox = this.boundingBox;
var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
return size.length();
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.