_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q27200 | train | function() {
if ($(this).treegrid('isNode')) {
var parentNode = $(this).treegrid('getParentNode');
if (parentNode === null) {
if ($(this).treegrid('getNodeId') === $(this).treegrid('getRootNodes').last().treegrid('getNodeId')) {
return true;
}
} else {
if ($(this).treegrid('getNodeId') === parentNode.treegrid('getChildNodes').last().treegrid('getNodeId')) {
return true;
}
}
}
return false;
} | javascript | {
"resource": ""
} | |
q27201 | train | function() {
if ($(this).treegrid('isNode')) {
var parentNode = $(this).treegrid('getParentNode');
if (parentNode === null) {
if ($(this).treegrid('getNodeId') === $(this).treegrid('getRootNodes').first().treegrid('getNodeId')) {
return true;
}
} else {
if ($(this).treegrid('getNodeId') === parentNode.treegrid('getChildNodes').first().treegrid('getNodeId')) {
return true;
}
}
}
return false;
} | javascript | {
"resource": ""
} | |
q27202 | train | function() {
return $(this).each(function() {
var $this = $(this);
var expander = $this.treegrid('getSetting', 'getExpander').apply(this);
if (expander) {
if (!$this.treegrid('isCollapsed')) {
expander.removeClass($this.treegrid('getSetting', 'expanderCollapsedClass'));
expander.addClass($this.treegrid('getSetting', 'expanderExpandedClass'));
} else {
expander.removeClass($this.treegrid('getSetting', 'expanderExpandedClass'));
expander.addClass($this.treegrid('getSetting', 'expanderCollapsedClass'));
}
} else {
$this.treegrid('initExpander');
$this.treegrid('renderExpander');
}
});
} | javascript | {
"resource": ""
} | |
q27203 | formatMatchingConstraints | train | function formatMatchingConstraints(matchingConstraints) {
let ret = {};
if (typeof matchingConstraints === 'undefined' || matchingConstraints === null) {
throw new TypeError('Constraints cannot be undefined or null');
}
if (!isPlainObject(matchingConstraints)) {
ret.callbackId = matchingConstraints;
} else {
ret = Object.assign({}, matchingConstraints);
}
return ret;
} | javascript | {
"resource": ""
} |
q27204 | validateConstraints | train | function validateConstraints(matchingConstraints) {
if (matchingConstraints.callbackId &&
!(isString(matchingConstraints.callbackId) || isRegExp(matchingConstraints.callbackId))) {
return new TypeError('Callback ID must be a string or RegExp');
}
if (matchingConstraints.blockId &&
!(isString(matchingConstraints.blockId) || isRegExp(matchingConstraints.blockId))) {
return new TypeError('Block ID must be a string or RegExp');
}
if (matchingConstraints.actionId &&
!(isString(matchingConstraints.actionId) || isRegExp(matchingConstraints.actionId))) {
return new TypeError('Action ID must be a string or RegExp');
}
return false;
} | javascript | {
"resource": ""
} |
q27205 | validateOptionsConstraints | train | function validateOptionsConstraints(optionsConstraints) {
if (optionsConstraints.within &&
!(optionsConstraints.within === 'interactive_message' ||
optionsConstraints.within === 'block_actions' ||
optionsConstraints.within === 'dialog')
) {
return new TypeError('Within must be \'block_actions\', \'interactive_message\' or \'dialog\'');
}
// We don't need to validate unfurl, we'll just cooerce it to a boolean
return false;
} | javascript | {
"resource": ""
} |
q27206 | slackSlashCommand | train | function slackSlashCommand(req, res, next) {
if (req.body.command === '/interactive-example') {
const type = req.body.text.split(' ')[0];
if (type === 'button') {
res.json(interactiveButtons);
} else if (type === 'menu') {
res.json(interactiveMenu);
} else if (type === 'dialog') {
res.send();
web.dialog.open({
trigger_id: req.body.trigger_id,
dialog,
}).catch((error) => {
return axios.post(req.body.response_url, {
text: `An error occurred while opening the dialog: ${error.message}`,
});
}).catch(console.error);
} else {
res.send('Use this command followed by `button`, `menu`, or `dialog`.');
}
} else {
next();
}
} | javascript | {
"resource": ""
} |
q27207 | train | function(settings) {
this.addSettings(settings);
// register the service worker
_serviceWorker.register(_settings['service-worker-url'], _settings['registration-options']).then(function(registration) {
// Registration was successful
if (_debugState) {
console.log('Service worker registration successful with scope: %c'+registration.scope, _debugStyle);
}
// Send the settings to the service worker
var messenger = registration.installing || _serviceWorker.controller || registration.active;
messenger.postMessage({'action': 'set-settings', 'settings': _settings});
}).catch(function(err) {
// registration failed :(
if (_debugState) {
console.log('Service worker registration failed: %c'+err, _debugStyle);
}
});
} | javascript | {
"resource": ""
} | |
q27208 | train | function(settings) {
settings = settings || {};
// if we got a string, instead of a settings object, use that string as the content
if (typeof settings === 'string') {
settings = { content: settings };
}
// add new settings to our settings object
[
'content',
'content-url',
'assets',
'service-worker-url',
'cache-version',
].forEach(function(settingName) {
if (settings[settingName] !== undefined) {
_settings[settingName] = settings[settingName];
}
});
// Add scope setting
if (settings['scope'] !== undefined) {
_settings['registration-options']['scope'] = settings['scope'];
}
} | javascript | {
"resource": ""
} | |
q27209 | train | function(input) {
input = input.toString();
var hash = 0, i, chr, len = input.length;
if (len === 0) {
return hash;
}
for (i = 0; i < len; i++) {
chr = input.charCodeAt(i);
hash = (hash << 5) - hash + chr;
hash |= 0;
}
return hash;
} | javascript | {
"resource": ""
} | |
q27210 | train | function(useCached) {
var rect = this._cachedViewportRect;
if (useCached) return rect;
// total transform is viewport transform combined with this layer's transform
var viewport = Crafty.viewport;
var options = this.options;
var scale = Math.pow(viewport._scale, options.scaleResponse);
rect._scale = scale;
rect._w = viewport._width / scale;
rect._h = viewport._height / scale;
// This particular transformation is designed such that,
// if a combination pan/scale keeps the center of the screen fixed for a layer with x/y response of 1,
// then it will also be fixed for layers with other values for x/y response
// (note that the second term vanishes when either the response or scale are 1)
rect._x =
options.xResponse * -viewport._x -
0.5 *
(options.xResponse - 1) *
(1 - 1 / scale) *
viewport._width;
rect._y =
options.yResponse * -viewport._y -
0.5 *
(options.yResponse - 1) *
(1 - 1 / scale) *
viewport._height;
return rect;
} | javascript | {
"resource": ""
} | |
q27211 | train | function(rect, outRect, useCached) {
var view = this._viewportRect(useCached),
scale = view._scale;
outRect = outRect || {};
outRect._x = rect._x * scale + Math.round(-view._x * scale);
outRect._y = rect._y * scale + Math.round(-view._y * scale);
outRect._w = rect._w * scale;
outRect._h = rect._h * scale;
return outRect;
} | javascript | {
"resource": ""
} | |
q27212 | train | function(drad) {
var cos = Math.cos(drad);
cos = -1e-10 < cos && cos < 1e-10 ? 0 : cos;
return cos;
} | javascript | {
"resource": ""
} | |
q27213 | train | function(v) {
//var theta = -1 * (v % 360); //angle always between 0 and 359
var difference = this._rotation - v;
// skip if there's no rotation!
if (difference === 0) return;
else this._rotation = v;
this._calculateMBR();
this.trigger("Rotate", difference);
} | javascript | {
"resource": ""
} | |
q27214 | train | function(x, y) {
if (x === this._x && y === this._y) return;
var old = Crafty.rectManager._pool.copy(this);
var mbr = this._mbr;
if (mbr) {
mbr._x -= this._x - x;
mbr._y -= this._y - y;
// cbr is a non-minimal bounding rectangle that contains both hitbox and mbr
// It will exist only when the collision hitbox sits outside the entity
if (this._cbr) {
this._cbr._x -= this._x - x;
this._cbr._y -= this._y - y;
}
}
this._x = x;
this._y = y;
this.trigger("Move", old);
this.trigger("Invalidate");
Crafty.rectManager._pool.recycle(old);
} | javascript | {
"resource": ""
} | |
q27215 | train | function(name, value) {
// Return if there is no change
if (this[name] === value) {
return;
}
//keep a reference of the old positions
var old = Crafty.rectManager._pool.copy(this);
var mbr;
//if rotation, use the rotate method
if (name === "_rotation") {
this._rotate(value); // _rotate triggers "Rotate"
//set the global Z and trigger reorder just in case
} else if (name === "_x" || name === "_y") {
// mbr is the minimal bounding rectangle of the entity
mbr = this._mbr;
if (mbr) {
mbr[name] -= this[name] - value;
// cbr is a non-minimal bounding rectangle that contains both hitbox and mbr
// It will exist only when the collision hitbox sits outside the entity
if (this._cbr) {
this._cbr[name] -= this[name] - value;
}
}
this[name] = value;
this.trigger("Move", old);
} else if (name === "_h" || name === "_w") {
mbr = this._mbr;
var oldValue = this[name];
this[name] = value;
if (mbr) {
this._calculateMBR();
}
if (name === "_w") {
this.trigger("Resize", {
axis: "w",
amount: value - oldValue
});
} else if (name === "_h") {
this.trigger("Resize", {
axis: "h",
amount: value - oldValue
});
}
this.trigger("Move", old);
} else if (name === "_z") {
var intValue = value << 0;
value = value === intValue ? intValue : intValue + 1;
this._globalZ = value * 100000 + this[0]; //magic number 10^5 is the max num of entities
this[name] = value;
this.trigger("Reorder");
}
//everything will assume the value
this[name] = value;
// flag for redraw
this.trigger("Invalidate");
Crafty.rectManager._pool.recycle(old);
} | javascript | {
"resource": ""
} | |
q27216 | train | function(eventName, e) {
// trigger event on MouseSystem itself
this.trigger(eventName, e);
// special case: MouseOver & MouseOut
var over = this.over,
closest = e.target;
if (eventName === "MouseMove" && over !== closest) {
// MouseOver target changed
// if old MouseOver target wasn't null, send MouseOut
if (over) {
e.eventName = "MouseOut";
e.target = over;
over.trigger("MouseOut", e);
e.eventName = "MouseMove";
e.target = closest;
}
// save new over entity
this.over = closest;
// if new MouseOver target isn't null, send MouseOver
if (closest) {
e.eventName = "MouseOver";
closest.trigger("MouseOver", e);
e.eventName = "MouseMove";
}
}
// TODO: move routing of events in future to controls system, make it similar to KeyboardSystem
// try to find closest element that will also receive mouse event, whatever the event is
if (closest) {
closest.trigger(eventName, e);
}
} | javascript | {
"resource": ""
} | |
q27217 | train | function(key, context) {
var first, keys, subkey;
if (typeof context === "undefined" || context === null) {
context = this;
}
if (key.indexOf(".") > -1) {
keys = key.split(".");
first = keys.shift();
subkey = keys.join(".");
return this._attr_get(keys.join("."), context[first]);
} else {
return context[key];
}
} | javascript | {
"resource": ""
} | |
q27218 | train | function() {
var data, silent, recursive;
if (typeof arguments[0] === "string") {
data = this._set_create_object(arguments[0], arguments[1]);
silent = !!arguments[2];
recursive = arguments[3] || arguments[0].indexOf(".") > -1;
} else {
data = arguments[0];
silent = !!arguments[1];
recursive = !!arguments[2];
}
if (!silent) {
this.trigger("Change", data);
}
if (recursive) {
this._recursive_extend(data, this);
} else {
this.extend.call(this, data);
}
return this;
} | javascript | {
"resource": ""
} | |
q27219 | train | function(key, value) {
var data = {},
keys,
first,
subkey;
if (key.indexOf(".") > -1) {
keys = key.split(".");
first = keys.shift();
subkey = keys.join(".");
data[first] = this._set_create_object(subkey, value);
} else {
data[key] = value;
}
return data;
} | javascript | {
"resource": ""
} | |
q27220 | train | function(new_data, original_data) {
var key;
for (key in new_data) {
if (new_data[key].constructor === Object) {
original_data[key] = this._recursive_extend(
new_data[key],
original_data[key]
);
} else {
original_data[key] = new_data[key];
}
}
return original_data;
} | javascript | {
"resource": ""
} | |
q27221 | train | function(event, fn) {
// Get handle to event, creating it if necessary
var callbacks = this._callbacks[event];
if (!callbacks) {
callbacks = this._callbacks[event] = (handlers[event] ||
(handlers[event] = {}))[this[0]] = [];
callbacks.context = this;
callbacks.depth = 0;
}
// Push to callback array
callbacks.push(fn);
} | javascript | {
"resource": ""
} | |
q27222 | train | function(event, data) {
if (!this._callbacks[event] || this.__callbacksFrozen) {
return;
}
var callbacks = this._callbacks[event];
// Callback loop; deletes dead callbacks, but only when it is safe to do so
var i,
l = callbacks.length;
// callbacks.depth tracks whether this function was invoked in the middle of a previous iteration through the same callback array
callbacks.depth++;
for (i = 0; i < l; i++) {
if (typeof callbacks[i] === "undefined") {
if (callbacks.depth <= 1) {
callbacks.splice(i, 1);
i--;
l--;
// Delete callbacks object if there are no remaining bound events
if (callbacks.length === 0) {
delete this._callbacks[event];
delete handlers[event][this[0]];
}
}
} else {
callbacks[i].call(this, data);
}
}
callbacks.depth--;
} | javascript | {
"resource": ""
} | |
q27223 | train | function(event, fn) {
if (!this._callbacks[event]) {
return;
}
var callbacks = this._callbacks[event];
// Iterate through and delete the callback functions that match
// They are spliced out when _runCallbacks is invoked, not here
// (This function might be called in the middle of a callback, which complicates the logic)
for (var i = 0; i < callbacks.length; i++) {
if (!fn || callbacks[i] === fn) {
delete callbacks[i];
}
}
} | javascript | {
"resource": ""
} | |
q27224 | train | function() {
if (!this._callbacks) return;
this.__callbacksFrozen = false;
for (var event in this._callbacks) {
if (this._callbacks[event]) {
// Remove the normal way, in case we've got a nested loop
this._unbindCallbacks(event);
// Also completely delete the registered callback from handlers
delete handlers[event][this[0]];
}
}
} | javascript | {
"resource": ""
} | |
q27225 | train | function(enabled) {
var style = this._div.style;
var camelize = Crafty.domHelper.camelize;
if (enabled) {
style[camelize("image-rendering")] = "optimizeSpeed"; /* legacy */
style[camelize("image-rendering")] =
"-moz-crisp-edges"; /* Firefox */
style[camelize("image-rendering")] = "-o-crisp-edges"; /* Opera */
style[camelize("image-rendering")] =
"-webkit-optimize-contrast"; /* Webkit (Chrome & Safari) */
style[camelize("-ms-interpolation-mode")] =
"nearest-neighbor"; /* IE */
style[camelize("image-rendering")] =
"optimize-contrast"; /* CSS3 proposed */
style[camelize("image-rendering")] =
"pixelated"; /* CSS4 proposed */
style[camelize("image-rendering")] =
"crisp-edges"; /* CSS4 proposed */
} else {
style[camelize("image-rendering")] = "optimizeQuality"; /* legacy */
style[camelize("-ms-interpolation-mode")] = "bicubic"; /* IE */
style[camelize("image-rendering")] = "auto"; /* CSS3 */
}
} | javascript | {
"resource": ""
} | |
q27226 | train | function() {
var style = this._div.style,
view = this._viewportRect();
var scale = view._scale;
var dx = -view._x * scale;
var dy = -view._y * scale;
style.transform = style[Crafty.support.prefix + "Transform"] =
"scale(" + scale + ", " + scale + ")";
style.left = Math.round(dx) + "px";
style.top = Math.round(dy) + "px";
style.zIndex = this.options.z;
} | javascript | {
"resource": ""
} | |
q27227 | train | function() {
var t;
for (var i = 0; i < this.bound_textures.length; i++) {
t = this.bound_textures[i];
t.unbind();
}
this.bound_textures = [];
this.active = null;
} | javascript | {
"resource": ""
} | |
q27228 | train | function(url, image, repeating) {
// gl is the context, webgl is the Crafty object containing prefs/etc
// var gl = this.gl;
var webgl = this.webgl;
// Check whether a texture that matches the one requested already exists
var id = "texture-(r:" + repeating + ")-" + url;
if (typeof this.registered_textures[id] !== "undefined")
return this.registered_textures[id];
// Create a texture, bind it to the next available unit
var t = new TextureWrapper(this, id);
this.registered_textures[id] = t;
this.bindTexture(t);
// Set the properties of the texture
t.setImage(image);
t.setFilter(webgl.texture_filter);
t.setRepeat(repeating);
return t;
} | javascript | {
"resource": ""
} | |
q27229 | train | function() {
var min_size = Infinity;
var index = null;
for (var i = 0; i < this.bound_textures.length; i++) {
var t = this.bound_textures[i];
if (t.size < min_size) {
min_size = t.size;
index = i;
}
}
return index;
} | javascript | {
"resource": ""
} | |
q27230 | train | function(t) {
// return if the texture is already bound
if (t.unit !== null) return;
var i = this.getAvailableUnit();
if (this.bound_textures[i]) {
this.unbindTexture(this.bound_textures[i]);
}
this.bound_textures[i] = t;
t.bind(i);
} | javascript | {
"resource": ""
} | |
q27231 | train | function(unit) {
var gl = this.gl;
this.unit = unit;
this.name = "TEXTURE" + unit;
this.manager.setActiveTexture(this);
gl.bindTexture(gl.TEXTURE_2D, this.glTexture);
} | javascript | {
"resource": ""
} | |
q27232 | train | function(image) {
if (!this.isActive())
throw "Trying to set image of texture that isn't active";
this.width = image.width;
this.height = image.height;
this.size = image.width * image.height;
this.powerOfTwo = !(
Math.log(image.width) / Math.LN2 !==
Math.floor(Math.log(image.width) / Math.LN2) ||
Math.log(image.height) / Math.LN2 !==
Math.floor(Math.log(image.height) / Math.LN2)
);
var gl = this.gl;
gl.texImage2D(
gl.TEXTURE_2D,
0,
gl.RGBA,
gl.RGBA,
gl.UNSIGNED_BYTE,
image
);
} | javascript | {
"resource": ""
} | |
q27233 | train | function(repeat) {
if (!this.isActive())
throw "Trying to set repeat property of texture that isn't active";
if (repeat && !this.powerOfTwo) {
throw "Can't create a repeating image whose dimensions aren't a power of 2 in WebGL contexts";
}
var gl = this.gl;
this.repeatMode = repeat ? gl.REPEAT : gl.CLAMP_TO_EDGE;
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, this.repeatMode);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, this.repeatMode);
} | javascript | {
"resource": ""
} | |
q27234 | train | function(shader, sampler_name, dimension_name) {
if (this.unit === null)
throw "Trying to use texture not set to a texture unit.";
var gl = this.gl;
gl.useProgram(shader);
// Set the texture buffer to use
gl.uniform1i(gl.getUniformLocation(shader, sampler_name), this.unit);
// Set the image dimensions
gl.uniform2f(
gl.getUniformLocation(shader, dimension_name),
this.width,
this.height
);
} | javascript | {
"resource": ""
} | |
q27235 | train | function(dpad, normalize) {
var x = 0,
y = 0;
// Sum up all active directions
for (var d in dpad.directions) {
var dir = dpad.directions[d];
if (!dir.active) continue;
x += dir.n.x;
y += dir.n.y;
}
// Mitigate rounding errors when close to zero movement
x = -1e-10 < x && x < 1e-10 ? 0 : x;
y = -1e-10 < y && y < 1e-10 ? 0 : y;
// Normalize
if (normalize) {
var m = Math.sqrt(x * x + y * y);
if (m > 0) {
x /= m;
y /= m;
}
}
dpad.x = x;
dpad.y = y;
} | javascript | {
"resource": ""
} | |
q27236 | RenderProgramWrapper | train | function RenderProgramWrapper(layer, shader) {
this.shader = shader;
this.layer = layer;
this.context = layer.context;
this.draw = function() {};
this.array_size = 16;
this.max_size = 1024;
this._indexArray = new Uint16Array(6 * this.array_size);
this._indexBuffer = layer.context.createBuffer();
} | javascript | {
"resource": ""
} |
q27237 | train | function(attributes) {
this.attributes = attributes;
this._attribute_table = {};
var offset = 0;
for (var i = 0; i < attributes.length; i++) {
var a = attributes[i];
this._attribute_table[a.name] = a;
a.bytes = a.bytes || Float32Array.BYTES_PER_ELEMENT;
a.type = a.type || this.context.FLOAT;
a.offset = offset;
a.location = this.context.getAttribLocation(this.shader, a.name);
this.context.enableVertexAttribArray(a.location);
offset += a.width;
}
// Stride is the full width including the last set
this.stride = offset;
// Create attribute array of correct size to hold max elements
this._attributeArray = new Float32Array(
this.array_size * 4 * this.stride
);
this._attributeBuffer = this.context.createBuffer();
this._registryHoles = [];
this._registrySize = 0;
} | javascript | {
"resource": ""
} | |
q27238 | train | function(size) {
if (this.array_size >= this.max_size) return;
var newsize = Math.min(size, this.max_size);
var newAttributeArray = new Float32Array(newsize * 4 * this.stride);
var newIndexArray = new Uint16Array(6 * newsize);
newAttributeArray.set(this._attributeArray);
newIndexArray.set(this._indexArray);
this._attributeArray = newAttributeArray;
this._indexArray = newIndexArray;
this.array_size = newsize;
} | javascript | {
"resource": ""
} | |
q27239 | train | function(e) {
if (this._registryHoles.length === 0) {
if (this._registrySize >= this.max_size) {
throw "Number of entities exceeds maximum limit.";
} else if (this._registrySize >= this.array_size) {
this.growArrays(2 * this.array_size);
}
e._glBufferIndex = this._registrySize;
this._registrySize++;
} else {
e._glBufferIndex = this._registryHoles.pop();
}
} | javascript | {
"resource": ""
} | |
q27240 | train | function(e) {
if (typeof e._glBufferIndex === "number")
this._registryHoles.push(e._glBufferIndex);
e._glBufferIndex = null;
} | javascript | {
"resource": ""
} | |
q27241 | train | function() {
var gl = this.context;
gl.useProgram(this.shader);
gl.bindBuffer(gl.ARRAY_BUFFER, this._attributeBuffer);
var a,
attributes = this.attributes;
// Process every attribute
for (var i = 0; i < attributes.length; i++) {
a = attributes[i];
gl.vertexAttribPointer(
a.location,
a.width,
a.type,
false,
this.stride * a.bytes,
a.offset * a.bytes
);
}
// For now, special case the need for texture objects
var t = this.texture_obj;
if (t && t.unit === null) {
this.layer.texture_manager.bindTexture(t);
}
this.index_pointer = 0;
} | javascript | {
"resource": ""
} | |
q27242 | train | function(offset) {
var index = this._indexArray,
l = this.index_pointer;
index[0 + l] = 0 + offset;
index[1 + l] = 1 + offset;
index[2 + l] = 2 + offset;
index[3 + l] = 1 + offset;
index[4 + l] = 2 + offset;
index[5 + l] = 3 + offset;
this.index_pointer += 6;
} | javascript | {
"resource": ""
} | |
q27243 | train | function() {
var gl = this.context;
gl.bindBuffer(gl.ARRAY_BUFFER, this._attributeBuffer);
gl.bufferData(gl.ARRAY_BUFFER, this._attributeArray, gl.STATIC_DRAW);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer);
gl.bufferData(
gl.ELEMENT_ARRAY_BUFFER,
this._indexArray,
gl.STATIC_DRAW
);
gl.drawElements(gl.TRIANGLES, this.index_pointer, gl.UNSIGNED_SHORT, 0);
} | javascript | {
"resource": ""
} | |
q27244 | train | function(src, type) {
var gl = this.context;
var shader = gl.createShader(type);
gl.shaderSource(shader, src);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
throw gl.getShaderInfoLog(shader);
}
return shader;
} | javascript | {
"resource": ""
} | |
q27245 | train | function(shader) {
var gl = this.context;
var fragmentShader = this._compileShader(
shader.fragmentCode,
gl.FRAGMENT_SHADER
);
var vertexShader = this._compileShader(
shader.vertexCode,
gl.VERTEX_SHADER
);
var shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
throw "Could not initialise shaders";
}
shaderProgram.viewport = gl.getUniformLocation(
shaderProgram,
"uViewport"
);
return shaderProgram;
} | javascript | {
"resource": ""
} | |
q27246 | train | function() {
var c = this._canvas;
c.width = Crafty.viewport.width;
c.height = Crafty.viewport.height;
var gl = this.context;
gl.viewportWidth = c.width;
gl.viewportHeight = c.height;
} | javascript | {
"resource": ""
} | |
q27247 | train | function(rect) {
rect = rect || this._viewportRect();
var gl = this.context;
// Set viewport and clear it
gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
//Set the viewport uniform variables used by each registered program
var programs = this.programs;
if (this._dirtyViewport) {
var view = this._viewportRect();
for (var comp in programs) {
programs[comp].setViewportUniforms(view, this.options);
}
this._dirtyViewport = false;
}
// Search for any entities in the given area (viewport unless otherwise specified)
var q = Crafty.map.search(rect),
i = 0,
l = q.length,
current;
//From all potential candidates, build a list of visible entities, then sort by zorder
var visible_gl = this.visible_gl;
visible_gl.length = 0;
for (i = 0; i < l; i++) {
current = q[i];
if (
current._visible &&
current.program &&
current._drawLayer === this
) {
visible_gl.push(current);
}
}
visible_gl.sort(this._sort);
l = visible_gl.length;
// Now iterate through the z-sorted entities to be rendered
// Each entity writes it's data into a typed array
// The entities are rendered in batches, where the entire array is copied to a buffer in one operation
// A batch is rendered whenever the next element needs to use a different type of program
// Therefore, you get better performance by grouping programs by z-order if possible.
// (Each sprite sheet will use a different program, but multiple sprites on the same sheet can be rendered in one batch)
var shaderProgram = null;
for (i = 0; i < l; i++) {
current = visible_gl[i];
if (shaderProgram !== current.program) {
if (shaderProgram !== null) {
shaderProgram.renderBatch();
}
shaderProgram = current.program;
shaderProgram.index_pointer = 0;
shaderProgram.switchTo();
}
current.draw();
current._changed = false;
}
if (shaderProgram !== null) {
shaderProgram.renderBatch();
}
} | javascript | {
"resource": ""
} | |
q27248 | train | function(propertyName) {
// could check for DOM component, but this event should only be fired by such an entity!
// Rather than triggering Invalidate on each of these, we rely on css() triggering that event
switch (propertyName) {
case "textAlign":
this._textAlign = this._element.style.textAlign;
break;
case "color":
// Need to set individual color components, so use method
this.textColor(this._element.style.color);
break;
case "fontType":
this._textFont.type = this._element.style.fontType;
break;
case "fontWeight":
this._textFont.weight = this._element.style.fontWeight;
break;
case "fontSize":
this._textFont.size = this._element.style.fontSize;
break;
case "fontFamily":
this._textFont.family = this._element.style.fontFamily;
break;
case "fontVariant":
this._textFont.variant = this._element.style.fontVariant;
break;
case "lineHeight":
this._textFont.lineHeight = this._element.style.lineHeight;
break;
}
} | javascript | {
"resource": ""
} | |
q27249 | train | function() {
return (
this._textFont.type +
" " +
this._textFont.variant +
" " +
this._textFont.weight +
" " +
this._textFont.size +
" / " +
this._textFont.lineHeight +
" " +
this._textFont.family
);
} | javascript | {
"resource": ""
} | |
q27250 | train | function(compName, shader) {
this.program = this._drawLayer.getProgramWrapper(compName, shader);
// Needs to know where in the big array we are!
this.program.registerEntity(this);
// Shader program means ready
this.ready = true;
} | javascript | {
"resource": ""
} | |
q27251 | train | function() {
this.supported = {};
// Without support, no formats are supported
if (!Crafty.support.audio) return;
var audio = this.audioElement(),
canplay;
for (var i in this.codecs) {
canplay = audio.canPlayType(this.codecs[i]);
if (canplay !== "" && canplay !== "no") {
this.supported[i] = true;
} else {
this.supported[i] = false;
}
}
} | javascript | {
"resource": ""
} | |
q27252 | train | function() {
for (var i = 0; i < this.channels.length; i++) {
var chan = this.channels[i];
/*
* Second test looks for stuff that's out of use,
* but fallen foul of Chromium bug 280417
*/
if (
chan.active === false ||
(chan.obj.ended &&
chan.repeat <= this.sounds[chan.id].played)
) {
chan.active = true;
return chan;
}
}
// If necessary, create a new element, unless we've already reached the max limit
if (i < this.maxChannels) {
var c = {
obj: this.audioElement(),
active: true,
// Checks that the channel is being used to play sound id
_is: function(id) {
return this.id === id && this.active;
}
};
this.channels.push(c);
return c;
}
// In that case, return null
return null;
} | javascript | {
"resource": ""
} | |
q27253 | train | function(layer) {
if (!this.img || !layer) return;
if (layer.type === "Canvas") {
this._pattern = this._drawContext.createPattern(
this.img,
this._repeat
);
} else if (layer.type === "WebGL") {
this._establishShader(
"image:" + this.__image,
Crafty.defaultShader("Image")
);
this.program.setTexture(
this._drawLayer.makeTexture(
this.__image,
this.img,
this._repeat !== "no-repeat"
)
);
}
if (this._repeat === "no-repeat") {
this.w = this.w || this.img.width;
this.h = this.h || this.img.height;
}
this.ready = true;
this.trigger("Invalidate");
} | javascript | {
"resource": ""
} | |
q27254 | train | function() {
var comp,
c = this.__c,
str = "";
for (comp in c) {
str += " " + comp;
}
str = str.substr(1);
this._element.className = str;
} | javascript | {
"resource": ""
} | |
q27255 | train | function() {
if (
Crafty.loggingEnabled &&
(typeof window !== "undefined" ? window.console : console) &&
console.log
) {
console.log.apply(console, arguments);
}
} | javascript | {
"resource": ""
} | |
q27256 | train | function(e) {
var dx,
dy,
rot = this.rotation * DEG_TO_RAD,
points = this.map.points;
// Depending on the change of axis, move the corners of the rectangle appropriately
if (e.axis === "w") {
if (rot) {
dx = e.amount * Math.cos(rot);
dy = e.amount * Math.sin(rot);
} else {
dx = e.amount;
dy = 0;
}
// "top right" point shifts on change of w
points[2] += dx;
points[3] += dy;
} else {
if (rot) {
dy = e.amount * Math.cos(rot);
dx = -e.amount * Math.sin(rot);
} else {
dx = 0;
dy = e.amount;
}
// "bottom left" point shifts on change of h
points[6] += dx;
points[7] += dy;
}
// "bottom right" point shifts on either change
points[4] += dx;
points[5] += dy;
} | javascript | {
"resource": ""
} | |
q27257 | train | function(component, collisionData) {
return function() {
var hitData = this.hit(component);
if (collisionData.occurring === true) {
if (hitData !== null) {
// The collision is still in progress
return;
}
collisionData.occurring = false;
this.trigger("HitOff", component);
} else if (hitData !== null) {
collisionData.occurring = true;
this.trigger("HitOn", hitData);
}
};
} | javascript | {
"resource": ""
} | |
q27258 | train | function(e) {
if (!this._color) {
return;
}
if (e.type === "DOM") {
e.style.backgroundColor = this._color;
e.style.lineHeight = 0;
} else if (e.type === "canvas") {
e.ctx.fillStyle = this._color;
e.ctx.fillRect(e.pos._x, e.pos._y, e.pos._w, e.pos._h);
} else if (e.type === "webgl") {
e.program.draw(e, this);
}
} | javascript | {
"resource": ""
} | |
q27259 | train | function(eventName, e) {
// trigger event on TouchSystem itself
this.trigger(eventName, e);
var identifier = e.identifier,
closest = e.target,
over = this.overs[identifier];
if (over) {
// if old TouchOver target wasn't null, send TouchOut
if (
(eventName === "TouchMove" && over !== closest) || // if TouchOver target changed
eventName === "TouchEnd" ||
eventName === "TouchCancel"
) {
// or TouchEnd occurred
e.eventName = "TouchOut";
e.target = over;
e.entity = over; // DEPRECATED: remove this in upcoming release
over.trigger("TouchOut", e);
e.eventName = eventName;
e.target = closest;
e.entity = closest; // DEPRECATED: remove this in upcoming release
// delete old over entity
delete this.overs[identifier];
}
}
// TODO: move routing of events in future to controls system, make it similar to KeyboardSystem
// try to find closest element that will also receive touch event, whatever the event is
if (closest) {
closest.trigger(eventName, e);
}
if (closest) {
// if new TouchOver target isn't null, send TouchOver
if (
eventName === "TouchStart" || // if TouchStart occurred
(eventName === "TouchMove" && over !== closest)
) {
// or TouchOver target changed
e.eventName = "TouchOver";
closest.trigger("TouchOver", e);
e.eventName = eventName;
// save new over entity
this.overs[identifier] = closest;
}
}
} | javascript | {
"resource": ""
} | |
q27260 | env | train | function env(envName, configSetters) {
assertConfigSetters(configSetters)
const currentEnv = process.env.NODE_ENV || 'development'
if (currentEnv !== envName) {
return () => config => config
} else {
return group(configSetters)
}
} | javascript | {
"resource": ""
} |
q27261 | when | train | function when(condition, configSetters) {
assertConfigSetters(configSetters)
if (condition) {
return group(configSetters)
} else {
return () => config => config
}
} | javascript | {
"resource": ""
} |
q27262 | parseVersion | train | function parseVersion(versionString) {
const [release, prerelease] = versionString.split('-')
const splitRelease = release.split('.').map(number => parseInt(number, 10))
return {
major: splitRelease[0],
minor: splitRelease[1],
patch: splitRelease[2],
prerelease: prerelease || '',
raw: versionString
}
} | javascript | {
"resource": ""
} |
q27263 | setEnv | train | function setEnv(constants) {
const setter = context => prevConfig => {
context.setEnv = Object.assign({}, context.setEnv, toObject(constants))
return prevConfig
}
return Object.assign(setter, { post: addEnvironmentPlugin })
} | javascript | {
"resource": ""
} |
q27264 | group | train | function group(configSetters) {
assertConfigSetters(configSetters)
const pre = getHooks(configSetters, 'pre')
const post = getHooks(configSetters, 'post')
const groupBlock = context => config => invokeConfigSetters(configSetters, context, config)
return Object.assign(groupBlock, { pre, post })
} | javascript | {
"resource": ""
} |
q27265 | assertConfigSetters | train | function assertConfigSetters(configSetters) {
if (!Array.isArray(configSetters)) {
throw new Error(
`Expected parameter 'configSetters' to be an array of functions. Instead got ${configSetters}.`
)
}
if (!configSetters.every(_.isFunction)) {
const invalidElementIndex = configSetters.findIndex(setter => !_.isFunction(setter))
throw new Error(
`Expected parameter 'configSetters' to be an array of functions. ` +
`Element at index ${invalidElementIndex} is invalid: ${configSetters[invalidElementIndex]}.`
)
}
} | javascript | {
"resource": ""
} |
q27266 | createConfig | train | function createConfig(initialContext, configSetters) {
if (!initialContext) {
throw new Error(`No initial context passed.`)
}
assertConfigSetters(configSetters)
const baseConfig = {
resolve: {
// Explicitly define default extensions, otherwise blocks will overwrite them instead of extending
extensions: ['.js', '.json']
},
// Less noisy than default settings
stats: {
children: false,
chunks: false,
modules: false,
reasons: false
},
module: {
rules: []
},
plugins: []
}
invokePreHooks(configSetters, initialContext)
const config = invokeConfigSetters(configSetters, initialContext, baseConfig)
const postProcessedConfig = invokePostHooks(configSetters, initialContext, config)
return postProcessedConfig
} | javascript | {
"resource": ""
} |
q27267 | ngSwaggerGen | train | function ngSwaggerGen(options) {
if (typeof options.swagger != 'string') {
console.error("Swagger file not specified in the 'swagger' option");
process.exit(1);
}
var globalTunnel = require('global-tunnel-ng');
globalTunnel.initialize();
$RefParser.bundle(options.swagger, { dereference: { circular: false } }).then(
data => {
doGenerate(data, options);
},
err => {
console.error(
`Error reading swagger location ${options.swagger}: ${err}`
);
}
).catch(function (error) {
console.error(`Error: ${error}`);
});
} | javascript | {
"resource": ""
} |
q27268 | train | function(template, model, file) {
var code = Mustache.render(template, model, templates)
.replace(/[^\S\r\n]+$/gm, '');
fs.writeFileSync(file, code, 'UTF-8');
console.info('Wrote ' + file);
} | javascript | {
"resource": ""
} | |
q27269 | applyTagFilter | train | function applyTagFilter(models, services, options) {
var i;
// Normalize the included tag names
const includeTags = options.includeTags;
var included = null;
if (includeTags && includeTags.length > 0) {
included = [];
for (i = 0; i < includeTags.length; i++) {
included.push(tagName(includeTags[i], options));
}
}
// Normalize the excluded tag names
const excludeTags = options.excludeTags;
var excluded = null;
if (excludeTags && excludeTags.length > 0) {
excluded = [];
for (i = 0; i < excludeTags.length; i++) {
excluded.push(tagName(excludeTags[i], options));
}
}
// Filter out the unused models
var ignoreUnusedModels = options.ignoreUnusedModels !== false;
var usedModels = new Set();
const addToUsed = (dep) => usedModels.add(dep);
for (var serviceName in services) {
var include =
(!included || included.indexOf(serviceName) >= 0) &&
(!excluded || excluded.indexOf(serviceName) < 0);
if (!include) {
// This service is skipped - remove it
console.info(
'Ignoring service ' + serviceName + ' because it was not included'
);
delete services[serviceName];
} else if (ignoreUnusedModels) {
// Collect the models used by this service
var service = services[serviceName];
service.serviceDependencies.forEach(addToUsed);
service.serviceErrorDependencies.forEach(addToUsed);
}
}
if (ignoreUnusedModels) {
// Collect the model dependencies of models, so unused can be removed
var allDependencies = new Set();
usedModels.forEach(dep =>
collectDependencies(allDependencies, dep, models)
);
// Remove all models that are unused
for (var modelName in models) {
var model = models[modelName];
if (!allDependencies.has(model.modelClass)) {
// This model is not used - remove it
console.info(
'Ignoring model ' +
modelName +
' because it was not used by any service'
);
delete models[modelName];
}
}
}
} | javascript | {
"resource": ""
} |
q27270 | collectDependencies | train | function collectDependencies(dependencies, model, models) {
if (!model || dependencies.has(model.modelClass)) {
return;
}
dependencies.add(model.modelClass);
if (model.modelDependencies) {
model.modelDependencies.forEach((dep) =>
collectDependencies(dependencies, dep, models)
);
}
} | javascript | {
"resource": ""
} |
q27271 | toFileName | train | function toFileName(typeName) {
var result = '';
var wasLower = false;
for (var i = 0; i < typeName.length; i++) {
var c = typeName.charAt(i);
var isLower = /[a-z]/.test(c);
if (!isLower && wasLower) {
result += '-';
}
result += c.toLowerCase();
wasLower = isLower;
}
return result;
} | javascript | {
"resource": ""
} |
q27272 | toClassName | train | function toClassName(name) {
var result = '';
var upNext = false;
for (var i = 0; i < name.length; i++) {
var c = name.charAt(i);
var valid = /[\w]/.test(c);
if (!valid) {
upNext = true;
} else if (upNext) {
result += c.toUpperCase();
upNext = false;
} else if (result === '') {
result = c.toUpperCase();
} else {
result += c;
}
}
if (/[0-9]/.test(result.charAt(0))) {
result = '_' + result;
}
return result;
} | javascript | {
"resource": ""
} |
q27273 | simpleRef | train | function simpleRef(ref) {
if (!ref) {
return null;
}
var index = ref.lastIndexOf('/');
if (index >= 0) {
ref = ref.substr(index + 1);
}
return toClassName(ref);
} | javascript | {
"resource": ""
} |
q27274 | toEnumName | train | function toEnumName(value) {
var result = '';
var wasLower = false;
for (var i = 0; i < value.length; i++) {
var c = value.charAt(i);
var isLower = /[a-z]/.test(c);
if (!isLower && wasLower) {
result += '_';
}
result += c.toUpperCase();
wasLower = isLower;
}
if (!isNaN(value[0])) {
result = '_' + result;
}
result = result.replace(/[^\w]/g, '_');
result = result.replace(/_+/g, '_');
return result;
} | javascript | {
"resource": ""
} |
q27275 | toComments | train | function toComments(text, level) {
var indent = '';
var i;
for (i = 0; i < level; i++) {
indent += ' ';
}
if (text == null || text.length === 0) {
return indent;
}
const lines = text.trim().split('\n');
var result = '\n' + indent + '/**\n';
lines.forEach(line => {
result += indent + ' *' + (line === '' ? '' : ' ' + line) + '\n';
});
result += indent + ' */\n' + indent;
return result;
} | javascript | {
"resource": ""
} |
q27276 | mergeTypes | train | function mergeTypes(...types) {
let allTypes = [];
types.forEach(type => {
(type.allTypes || [type]).forEach(type => {
if (allTypes.indexOf(type) < 0) allTypes.push(type);
});
});
return allTypes;
} | javascript | {
"resource": ""
} |
q27277 | processProperties | train | function processProperties(swagger, properties, requiredProperties) {
var result = {};
for (var name in properties) {
var property = properties[name];
var descriptor = {
propertyName: name.indexOf('-') === -1 ? name : `"${name}"`,
propertyComments: toComments(property.description, 1),
propertyRequired: requiredProperties.indexOf(name) >= 0,
propertyType: propertyType(property),
};
result[name] = descriptor;
}
return result;
} | javascript | {
"resource": ""
} |
q27278 | resolveRef | train | function resolveRef(swagger, ref) {
if (ref.indexOf('#/') != 0) {
console.error('Resolved references must start with #/. Current: ' + ref);
process.exit(1);
}
var parts = ref.substr(2).split('/');
var result = swagger;
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
result = result[part];
}
return result === swagger ? {} : result;
} | javascript | {
"resource": ""
} |
q27279 | toIdentifier | train | function toIdentifier(string) {
var result = '';
var wasSep = false;
for (var i = 0; i < string.length; i++) {
var c = string.charAt(i);
if (/[a-zA-Z0-9]/.test(c)) {
if (wasSep) {
c = c.toUpperCase();
wasSep = false;
}
result += c;
} else {
wasSep = true;
}
}
return result;
} | javascript | {
"resource": ""
} |
q27280 | tagName | train | function tagName(tag, options) {
if (tag == null || tag === '') {
tag = options.defaultTag || 'Api';
}
tag = toIdentifier(tag);
return tag.charAt(0).toUpperCase() + (tag.length == 1 ? '' : tag.substr(1));
} | javascript | {
"resource": ""
} |
q27281 | operationId | train | function operationId(given, method, url, allKnown) {
var id;
var generate = given == null;
if (generate) {
id = toIdentifier(method + url);
} else {
id = toIdentifier(given);
}
var duplicated = allKnown.has(id);
if (duplicated) {
var i = 1;
while (allKnown.has(id + '_' + i)) {
i++;
}
id = id + '_' + i;
}
if (generate) {
console.warn(
"Operation '" +
method +
"' on '" +
url +
"' defines no operationId. Assuming '" +
id +
"'."
);
} else if (duplicated) {
console.warn(
"Operation '" +
method +
"' on '" +
url +
"' defines a duplicated operationId: " +
given +
'. ' +
"Assuming '" +
id +
"'."
);
}
allKnown.add(id);
return id;
} | javascript | {
"resource": ""
} |
q27282 | train | function (image) {
for (var i = 0; i < cache.length; i++) {
if (cache[i].src === image.src) {
return cache[i];
}
}
cache.push(image);
return image;
} | javascript | {
"resource": ""
} | |
q27283 | train | function () {
if (oldVideoWrapper) {
oldVideoWrapper.stop();
oldVideoWrapper.destroy();
}
$oldItemWrapper.remove();
// Resume the slideshow
if (!that.paused && that.images.length > 1) {
that.cycle();
}
// Now we can clear the background on the element, to spare memory
if (!that.options.bypassCss && !that.isBody) {
that.$container.css('background-image', 'none');
}
// Trigger the "after" and "show" events
// "show" is being deprecated
$(['after', 'show']).each(function () {
that.$container.trigger($.Event('backstretch.' + this, evtOptions), [that, newIndex]);
});
if (isVideo) {
that.videoWrapper.play();
}
} | javascript | {
"resource": ""
} | |
q27284 | train | function(options) {
// Number of Tracks per output segment
// If greater than 1, we combine multiple
// tracks into a single segment
this.numberOfTracks = 0;
this.metadataStream = options.metadataStream;
this.videoTags = [];
this.audioTags = [];
this.videoTrack = null;
this.audioTrack = null;
this.pendingCaptions = [];
this.pendingMetadata = [];
this.pendingTracks = 0;
this.processedTracks = 0;
CoalesceStream.prototype.init.call(this);
// Take output from multiple
this.push = function(output) {
// buffer incoming captions until the associated video segment
// finishes
if (output.text) {
return this.pendingCaptions.push(output);
}
// buffer incoming id3 tags until the final flush
if (output.frames) {
return this.pendingMetadata.push(output);
}
if (output.track.type === 'video') {
this.videoTrack = output.track;
this.videoTags = output.tags;
this.pendingTracks++;
}
if (output.track.type === 'audio') {
this.audioTrack = output.track;
this.audioTags = output.tags;
this.pendingTracks++;
}
};
} | javascript | {
"resource": ""
} | |
q27285 | webworkifyDebug | train | function webworkifyDebug (worker) {
var targetA = new EventTarget(),
targetB = new EventTarget();
targetA.setTarget(targetB);
targetB.setTarget(targetA);
worker(targetA);
return targetB;
} | javascript | {
"resource": ""
} |
q27286 | train | function () {
var data = this.data;
// If true, show wireframes around physics bodies.
this.debug = data.debug;
this.callbacks = {beforeStep: [], step: [], afterStep: []};
this.listeners = {};
this.driver = null;
switch (data.driver) {
case 'local':
this.driver = new LocalDriver();
break;
case 'network':
this.driver = new NetworkDriver(data.networkUrl);
break;
case 'worker':
this.driver = new WorkerDriver({
fps: data.workerFps,
engine: data.workerEngine,
interpolate: data.workerInterpolate,
interpolationBufferSize: data.workerInterpBufferSize,
debug: data.workerDebug
});
break;
default:
throw new Error('[physics] Driver not recognized: "%s".', data.driver);
}
this.driver.init({
quatNormalizeSkip: 0,
quatNormalizeFast: false,
solverIterations: data.iterations,
gravity: data.gravity
});
this.driver.addMaterial({name: 'defaultMaterial'});
this.driver.addMaterial({name: 'staticMaterial'});
this.driver.addContactMaterial('defaultMaterial', 'defaultMaterial', {
friction: data.friction,
restitution: data.restitution,
contactEquationStiffness: data.contactEquationStiffness,
contactEquationRelaxation: data.contactEquationRelaxation,
frictionEquationStiffness: data.frictionEquationStiffness,
frictionEquationRegularization: data.frictionEquationRegularization
});
this.driver.addContactMaterial('staticMaterial', 'defaultMaterial', {
friction: 1.0,
restitution: 0.0,
contactEquationStiffness: data.contactEquationStiffness,
contactEquationRelaxation: data.contactEquationRelaxation,
frictionEquationStiffness: data.frictionEquationStiffness,
frictionEquationRegularization: data.frictionEquationRegularization
});
} | javascript | {
"resource": ""
} | |
q27287 | train | function (body) {
var driver = this.driver;
body.__applyImpulse = body.applyImpulse;
body.applyImpulse = function () {
driver.applyBodyMethod(body, 'applyImpulse', arguments);
};
body.__applyForce = body.applyForce;
body.applyForce = function () {
driver.applyBodyMethod(body, 'applyForce', arguments);
};
body.updateProperties = function () {
driver.updateBodyProperties(body);
};
this.listeners[body.id] = function (e) { body.el.emit('collide', e); };
body.addEventListener('collide', this.listeners[body.id]);
this.driver.addBody(body);
} | javascript | {
"resource": ""
} | |
q27288 | train | function (body) {
this.driver.removeBody(body);
body.removeEventListener('collide', this.listeners[body.id]);
delete this.listeners[body.id];
body.applyImpulse = body.__applyImpulse;
delete body.__applyImpulse;
body.applyForce = body.__applyForce;
delete body.__applyForce;
delete body.updateProperties;
} | javascript | {
"resource": ""
} | |
q27289 | train | function (component) {
var callbacks = this.callbacks;
if (component.beforeStep) callbacks.beforeStep.push(component);
if (component.step) callbacks.step.push(component);
if (component.afterStep) callbacks.afterStep.push(component);
} | javascript | {
"resource": ""
} | |
q27290 | train | function (component) {
var callbacks = this.callbacks;
if (component.beforeStep) {
callbacks.beforeStep.splice(callbacks.beforeStep.indexOf(component), 1);
}
if (component.step) {
callbacks.step.splice(callbacks.step.indexOf(component), 1);
}
if (component.afterStep) {
callbacks.afterStep.splice(callbacks.afterStep.indexOf(component), 1);
}
} | javascript | {
"resource": ""
} | |
q27291 | filter | train | function filter() {
var ret = [];
var labels = Array.prototype.slice.call(arguments);
labels.forEach(function(label) {
browsers.forEach(function(browser) {
if (label === 'bs_all') {
ret.push(browser);
} else if (browser._alias.match(new RegExp(label.slice(2) + '$'))) {
ret.push(browser);
}
});
});
return ret;
} | javascript | {
"resource": ""
} |
q27292 | guessFunctionName | train | function guessFunctionName(url, lineNo) {
var reFunctionArgNames = /function ([^(]*)\(([^)]*)\)/,
reGuessFunction = /['"]?([0-9A-Za-z$_]+)['"]?\s*[:=]\s*(function|eval|new Function)/,
line = '',
maxLines = 10,
source = getSource(url),
m;
if (!source.length) {
return UNKNOWN_FUNCTION;
}
// Walk backwards from the first line in the function until we find the line which
// matches the pattern above, which is the function definition
for (var i = 0; i < maxLines; ++i) {
line = source[lineNo - i] + line;
if (!_isUndefined(line)) {
if ((m = reGuessFunction.exec(line))) {
return m[1];
} else if ((m = reFunctionArgNames.exec(line))) {
return m[1];
}
}
}
return UNKNOWN_FUNCTION;
} | javascript | {
"resource": ""
} |
q27293 | gatherContext | train | function gatherContext(url, line) {
var source = getSource(url);
if (!source.length) {
return null;
}
var context = [],
// linesBefore & linesAfter are inclusive with the offending line.
// if linesOfContext is even, there will be one extra line
// *before* the offending line.
linesBefore = Math.floor(linesOfContext / 2),
// Add one extra line if linesOfContext is odd
linesAfter = linesBefore + (linesOfContext % 2),
start = Math.max(0, line - linesBefore - 1),
end = Math.min(source.length, line + linesAfter - 1);
line -= 1; // convert to 0-based index
for (var i = start; i < end; ++i) {
if (!_isUndefined(source[i])) {
context.push(source[i]);
}
}
return context.length > 0 ? context : null;
} | javascript | {
"resource": ""
} |
q27294 | escapeCodeAsRegExpForMatchingInsideHTML | train | function escapeCodeAsRegExpForMatchingInsideHTML(body) {
return escapeRegExp(body).replace('<', '(?:<|<)').replace('>', '(?:>|>)').replace('&', '(?:&|&)').replace('"', '(?:"|")').replace(/\s+/g, '\\s+');
} | javascript | {
"resource": ""
} |
q27295 | findSourceInLine | train | function findSourceInLine(fragment, url, line) {
var source = getSource(url),
re = new RegExp('\\b' + escapeRegExp(fragment) + '\\b'),
m;
line -= 1;
if (source && source.length > line && (m = re.exec(source[line]))) {
return m.index;
}
return null;
} | javascript | {
"resource": ""
} |
q27296 | computeStackTraceFromStacktraceProp | train | function computeStackTraceFromStacktraceProp(ex) {
// Access and store the stacktrace property before doing ANYTHING
// else to it because Opera is not very good at providing it
// reliably in other circumstances.
var stacktrace = ex.stacktrace;
var testRE = / line (\d+), column (\d+) in (?:<anonymous function: ([^>]+)>|([^\)]+))\((.*)\) in (.*):\s*$/i,
lines = stacktrace.split('\n'),
stack = [],
parts;
for (var i = 0, j = lines.length; i < j; i += 2) {
if ((parts = testRE.exec(lines[i]))) {
var element = {
'line': +parts[1],
'column': +parts[2],
'func': parts[3] || parts[4],
'args': parts[5] ? parts[5].split(',') : [],
'url': parts[6]
};
if (!element.func && element.line) {
element.func = guessFunctionName(element.url, element.line);
}
if (element.line) {
try {
element.context = gatherContext(element.url, element.line);
} catch (exc) {}
}
if (!element.context) {
element.context = [lines[i + 1]];
}
stack.push(element);
}
}
if (!stack.length) {
return null;
}
return {
'mode': 'stacktrace',
'name': ex.name,
'message': ex.message,
'url': document.location.href,
'stack': stack,
'useragent': navigator.userAgent
};
} | javascript | {
"resource": ""
} |
q27297 | augmentStackTraceWithInitialElement | train | function augmentStackTraceWithInitialElement(stackInfo, url, lineNo, message) {
var initial = {
'url': url,
'line': lineNo
};
if (initial.url && initial.line) {
stackInfo.incomplete = false;
if (!initial.func) {
initial.func = guessFunctionName(initial.url, initial.line);
}
if (!initial.context) {
initial.context = gatherContext(initial.url, initial.line);
}
var reference = / '([^']+)' /.exec(message);
if (reference) {
initial.column = findSourceInLine(reference[1], initial.url, initial.line);
}
if (stackInfo.stack.length > 0) {
if (stackInfo.stack[0].url === initial.url) {
if (stackInfo.stack[0].line === initial.line) {
return false; // already in stack trace
} else if (!stackInfo.stack[0].line && stackInfo.stack[0].func === initial.func) {
stackInfo.stack[0].line = initial.line;
stackInfo.stack[0].context = initial.context;
return false;
}
}
}
stackInfo.stack.unshift(initial);
stackInfo.partial = true;
return true;
} else {
stackInfo.incomplete = true;
}
return false;
} | javascript | {
"resource": ""
} |
q27298 | computeStackTrace | train | function computeStackTrace(ex, depth) {
var stack = null;
depth = (depth == null ? 0 : +depth);
try {
// This must be tried first because Opera 10 *destroys*
// its stacktrace property if you try to access the stack
// property first!!
stack = computeStackTraceFromStacktraceProp(ex);
if (stack) {
return stack;
}
} catch (e) {
if (debug) {
throw e;
}
}
try {
stack = computeStackTraceFromStackProp(ex);
if (stack) {
return stack;
}
} catch (e) {
if (debug) {
throw e;
}
}
try {
stack = computeStackTraceFromOperaMultiLineMessage(ex);
if (stack) {
return stack;
}
} catch (e) {
if (debug) {
throw e;
}
}
try {
stack = computeStackTraceByWalkingCallerChain(ex, depth + 1);
if (stack) {
return stack;
}
} catch (e) {
if (debug) {
throw e;
}
}
return {
'mode': 'failed'
};
} | javascript | {
"resource": ""
} |
q27299 | computeStackTraceOfCaller | train | function computeStackTraceOfCaller(depth) {
depth = (depth == null ? 0 : +depth) + 1; // "+ 1" because "ofCaller" should drop one frame
try {
throw new Error();
} catch (ex) {
return computeStackTrace(ex, depth + 1);
}
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.