_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q22300
|
measureTextHeight
|
train
|
function measureTextHeight(font) {
return font.fontData.capHeight * font.lineHeight * font.fontScale.y;
}
|
javascript
|
{
"resource": ""
}
|
q22301
|
set
|
train
|
function set(textAlign, scale) {
this.textAlign = textAlign; // updated scaled Size
if (scale) {
this.resize(scale);
}
this.isDirty = true;
return this;
}
|
javascript
|
{
"resource": ""
}
|
q22302
|
draw
|
train
|
function draw(renderer, text, x, y) {
// allows to provide backward compatibility when
// adding Bitmap Font to an object container
if (typeof this.ancestor === "undefined") {
// update cache
this.setText(text); // force update bounds
this.update(0); // save the previous global alpha value
var _alpha = renderer.globalAlpha();
renderer.setGlobalAlpha(_alpha * this.getOpacity());
} else {
// added directly to an object container
x = this.pos.x;
y = this.pos.y;
}
var strings = ("" + this._text).split("\n");
var lX = x;
var stringHeight = measureTextHeight(this);
var maxWidth = 0;
for (var i = 0; i < strings.length; i++) {
x = lX;
var string = me.utils.string.trimRight(strings[i]); // adjust x pos based on alignment value
var stringWidth = measureTextWidth(this, string);
switch (this.textAlign) {
case "right":
x -= stringWidth;
break;
case "center":
x -= stringWidth * 0.5;
break;
default:
break;
} // adjust y pos based on alignment value
switch (this.textBaseline) {
case "middle":
y -= stringHeight * 0.5;
break;
case "ideographic":
case "alphabetic":
case "bottom":
y -= stringHeight;
break;
default:
break;
} // update initial position if required
if (this.isDirty === true && typeof this.ancestor === "undefined") {
if (i === 0) {
this.pos.y = y;
}
if (maxWidth < stringWidth) {
maxWidth = stringWidth;
this.pos.x = x;
}
} // draw the string
var lastGlyph = null;
for (var c = 0, len = string.length; c < len; c++) {
// calculate the char index
var ch = string.charCodeAt(c);
var glyph = this.fontData.glyphs[ch];
var glyphWidth = glyph.width;
var glyphHeight = glyph.height;
var kerning = lastGlyph && lastGlyph.kerning ? lastGlyph.getKerning(ch) : 0; // draw it
if (glyphWidth !== 0 && glyphHeight !== 0) {
// some browser throw an exception when drawing a 0 width or height image
renderer.drawImage(this.fontImage, glyph.x, glyph.y, glyphWidth, glyphHeight, x + glyph.xoffset, y + glyph.yoffset * this.fontScale.y, glyphWidth * this.fontScale.x, glyphHeight * this.fontScale.y);
} // increment position
x += (glyph.xadvance + kerning) * this.fontScale.x;
lastGlyph = glyph;
} // increment line
y += stringHeight;
}
if (typeof this.ancestor === "undefined") {
// restore the previous global alpha value
renderer.setGlobalAlpha(_alpha);
} // clear the dirty flag
this.isDirty = false;
}
|
javascript
|
{
"resource": ""
}
|
q22303
|
_getFirstGlyph
|
train
|
function _getFirstGlyph() {
var keys = Object.keys(this.glyphs);
for (var i = 0; i < keys.length; i++) {
if (keys[i] > 32) {
return this.glyphs[keys[i]];
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q22304
|
train
|
function(id, internal) {
var self = this;
// If the sound hasn't loaded, add it to the load queue to stop when capable.
if (self._state !== 'loaded' || self._playLock) {
self._queue.push({
event: 'stop',
action: function() {
self.stop(id);
}
});
return self;
}
// If no id is passed, get all ID's to be stopped.
var ids = self._getSoundIds(id);
for (var i=0; i<ids.length; i++) {
// Clear the end timer.
self._clearTimer(ids[i]);
// Get the sound.
var sound = self._soundById(ids[i]);
if (sound) {
// Reset the seek position.
sound._seek = sound._start || 0;
sound._rateSeek = 0;
sound._paused = true;
sound._ended = true;
// Stop currently running fades.
self._stopFade(ids[i]);
if (sound._node) {
if (self._webAudio) {
// Make sure the sound's AudioBufferSourceNode has been created.
if (sound._node.bufferSource) {
if (typeof sound._node.bufferSource.stop === 'undefined') {
sound._node.bufferSource.noteOff(0);
} else {
sound._node.bufferSource.stop(0);
}
// Clean up the buffer source.
self._cleanBuffer(sound._node);
}
} else if (!isNaN(sound._node.duration) || sound._node.duration === Infinity) {
sound._node.currentTime = sound._start || 0;
sound._node.pause();
}
}
if (!internal) {
self._emit('stop', sound._id);
}
}
}
return self;
}
|
javascript
|
{
"resource": ""
}
|
|
q22305
|
train
|
function() {
var self = this;
// Stop playing any active sounds.
var sounds = self._sounds;
for (var i=0; i<sounds.length; i++) {
// Stop the sound if it is currently playing.
if (!sounds[i]._paused) {
self.stop(sounds[i]._id);
}
// Remove the source or disconnect.
if (!self._webAudio) {
// Set the source to 0-second silence to stop any downloading (except in IE).
var checkIE = /MSIE |Trident\//.test(Howler._navigator && Howler._navigator.userAgent);
if (!checkIE) {
sounds[i]._node.src = 'data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA';
}
// Remove any event listeners.
sounds[i]._node.removeEventListener('error', sounds[i]._errorFn, false);
sounds[i]._node.removeEventListener(Howler._canPlayEvent, sounds[i]._loadFn, false);
// Release the Audio object back to the pool.
Howler._releaseHtml5Audio(sounds[i]._node);
}
// Empty out all of the nodes.
delete sounds[i]._node;
// Make sure all timers are cleared out.
self._clearTimer(sounds[i]._id);
}
// Remove the references in the global Howler object.
var index = Howler._howls.indexOf(self);
if (index >= 0) {
Howler._howls.splice(index, 1);
}
// Delete this sound from the cache (if no other Howl is using it).
var remCache = true;
for (i=0; i<Howler._howls.length; i++) {
if (Howler._howls[i]._src === self._src || self._src.indexOf(Howler._howls[i]._src) >= 0) {
remCache = false;
break;
}
}
if (cache && remCache) {
delete cache[self._src];
}
// Clear global errors.
Howler.noAudio = false;
// Clear out `self`.
self._state = 'unloaded';
self._sounds = [];
self = null;
return null;
}
|
javascript
|
{
"resource": ""
}
|
|
q22306
|
soundLoadError
|
train
|
function soundLoadError(sound_name, onerror_cb) {
// check the retry counter
if (retry_counter++ > 3) {
// something went wrong
var errmsg = "melonJS: failed loading " + sound_name;
if (me.sys.stopOnAudioError === false) {
// disable audio
me.audio.disable(); // call error callback if defined
if (onerror_cb) {
onerror_cb();
} // warning
console.log(errmsg + ", disabling audio");
} else {
// throw an exception and stop everything !
throw new Error(errmsg);
} // else try loading again !
} else {
audioTracks[sound_name].load();
}
}
|
javascript
|
{
"resource": ""
}
|
q22307
|
autoDetectRenderer
|
train
|
function autoDetectRenderer(c, width, height, options) {
try {
return new me.WebGLRenderer(c, width, height, options);
} catch (e) {
return new me.CanvasRenderer(c, width, height, options);
}
}
|
javascript
|
{
"resource": ""
}
|
q22308
|
overlaps
|
train
|
function overlaps(rect) {
return rect.left < this.getWidth() && rect.right > 0 && rect.top < this.getHeight() && rect.bottom > 0;
}
|
javascript
|
{
"resource": ""
}
|
q22309
|
stroke
|
train
|
function stroke(shape, fill) {
if (shape.shapeType === "Rectangle") {
this.strokeRect(shape.left, shape.top, shape.width, shape.height, fill);
} else if (shape instanceof me.Line || shape instanceof me.Polygon) {
this.strokePolygon(shape, fill);
} else if (shape instanceof me.Ellipse) {
this.strokeEllipse(shape.pos.x, shape.pos.y, shape.radiusV.x, shape.radiusV.y, fill);
}
}
|
javascript
|
{
"resource": ""
}
|
q22310
|
createAtlas
|
train
|
function createAtlas(width, height, name, repeat) {
return {
"meta": {
"app": "melonJS",
"size": {
"w": width,
"h": height
},
"repeat": repeat || "no-repeat",
"image": "default"
},
"frames": [{
"filename": name || "default",
"frame": {
"x": 0,
"y": 0,
"w": width,
"h": height
}
}]
};
}
|
javascript
|
{
"resource": ""
}
|
q22311
|
getAtlas
|
train
|
function getAtlas(key) {
if (typeof key === "string") {
return this.atlases.get(key);
} else {
return this.atlases.values().next().value;
}
}
|
javascript
|
{
"resource": ""
}
|
q22312
|
fillArc
|
train
|
function fillArc(x, y, radius, start, end, antiClockwise) {
this.strokeArc(x, y, radius, start, end, antiClockwise || false, true);
}
|
javascript
|
{
"resource": ""
}
|
q22313
|
fillLine
|
train
|
function fillLine(startX, startY, endX, endY) {
this.strokeLine(startX, startY, endX, endY);
}
|
javascript
|
{
"resource": ""
}
|
q22314
|
strokeRect
|
train
|
function strokeRect(x, y, width, height) {
if (this.backBufferContext2D.globalAlpha < 1 / 255) {
// Fast path: don't draw fully transparent
return;
}
this.backBufferContext2D.strokeRect(x, y, width, height);
}
|
javascript
|
{
"resource": ""
}
|
q22315
|
createPattern
|
train
|
function createPattern(image, repeat) {
if (!me.Math.isPowerOfTwo(image.width) || !me.Math.isPowerOfTwo(image.height)) {
var src = typeof image.src !== "undefined" ? image.src : image;
throw new Error("[WebGL Renderer] " + src + " is not a POT texture " + "(" + image.width + "x" + image.height + ")");
}
var texture = new this.Texture(this.Texture.prototype.createAtlas.apply(this.Texture.prototype, [image.width, image.height, "pattern", repeat]), image); // FIXME: Remove old cache entry and texture when changing the repeat mode
this.compositor.uploadTexture(texture);
return texture;
}
|
javascript
|
{
"resource": ""
}
|
q22316
|
getContextGL
|
train
|
function getContextGL(canvas, transparent) {
if (typeof canvas === "undefined" || canvas === null) {
throw new Error("You must pass a canvas element in order to create " + "a GL context");
}
if (typeof transparent !== "boolean") {
transparent = true;
}
var attr = {
alpha: transparent,
antialias: this.settings.antiAlias,
depth: false,
stencil: true,
premultipliedAlpha: transparent,
failIfMajorPerformanceCaveat: this.settings.failIfMajorPerformanceCaveat
};
var gl = canvas.getContext("webgl", attr) || canvas.getContext("experimental-webgl", attr);
if (!gl) {
throw new Error("A WebGL context could not be created.");
}
return gl;
}
|
javascript
|
{
"resource": ""
}
|
q22317
|
setBlendMode
|
train
|
function setBlendMode(mode, gl) {
gl = gl || this.gl;
gl.enable(gl.BLEND);
switch (mode) {
case "multiply":
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
this.currentBlendMode = mode;
break;
default:
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
this.currentBlendMode = "normal";
break;
}
}
|
javascript
|
{
"resource": ""
}
|
q22318
|
scaleCanvas
|
train
|
function scaleCanvas(scaleX, scaleY) {
var w = this.canvas.width * scaleX;
var h = this.canvas.height * scaleY; // adjust CSS style for High-DPI devices
if (me.device.devicePixelRatio > 1) {
this.canvas.style.width = w / me.device.devicePixelRatio + "px";
this.canvas.style.height = h / me.device.devicePixelRatio + "px";
} else {
this.canvas.style.width = w + "px";
this.canvas.style.height = h + "px";
}
this.compositor.setProjection(this.canvas.width, this.canvas.height);
}
|
javascript
|
{
"resource": ""
}
|
q22319
|
save
|
train
|
function save() {
this._colorStack.push(this.currentColor.clone());
this._matrixStack.push(this.currentTransform.clone());
if (this.gl.isEnabled(this.gl.SCISSOR_TEST)) {
// FIXME avoid slice and object realloc
this._scissorStack.push(this.currentScissor.slice());
}
}
|
javascript
|
{
"resource": ""
}
|
q22320
|
strokePolygon
|
train
|
function strokePolygon(poly, fill) {
if (fill === true) {
this.fillPolygon(poly);
} else {
var len = poly.points.length,
points = this._glPoints,
i; // Grow internal points buffer if necessary
for (i = points.length; i < len; i++) {
points.push(new me.Vector2d());
} // calculate and draw all segments
for (i = 0; i < len; i++) {
points[i].x = poly.pos.x + poly.points[i].x;
points[i].y = poly.pos.y + poly.points[i].y;
}
this.compositor.drawLine(points, len);
}
}
|
javascript
|
{
"resource": ""
}
|
q22321
|
fillPolygon
|
train
|
function fillPolygon(poly) {
var points = poly.points;
var glPoints = this._glPoints;
var indices = poly.getIndices();
var x = poly.pos.x,
y = poly.pos.y; // Grow internal points buffer if necessary
for (i = glPoints.length; i < indices.length; i++) {
glPoints.push(new me.Vector2d());
} // calculate all vertices
for (var i = 0; i < indices.length; i++) {
glPoints[i].set(x + points[indices[i]].x, y + points[indices[i]].y);
} // draw all triangle
this.compositor.drawTriangle(glPoints, indices.length);
}
|
javascript
|
{
"resource": ""
}
|
q22322
|
translate
|
train
|
function translate(x, y) {
if (this.settings.subPixel === false) {
this.currentTransform.translate(~~x, ~~y);
} else {
this.currentTransform.translate(x, y);
}
}
|
javascript
|
{
"resource": ""
}
|
q22323
|
setProjection
|
train
|
function setProjection(w, h) {
this.flush();
this.gl.viewport(0, 0, w, h);
this.uMatrix.setTransform(2 / w, 0, 0, 0, -2 / h, 0, -1, 1, 1);
}
|
javascript
|
{
"resource": ""
}
|
q22324
|
compileProgram
|
train
|
function compileProgram(gl, vertex, fragment) {
var vertShader = compileShader(gl, gl.VERTEX_SHADER, vertex);
var fragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragment);
var program = gl.createProgram();
gl.attachShader(program, vertShader);
gl.attachShader(program, fragShader);
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
throw new Error("Error initializing Shader " + this + "\n" + "gl.VALIDATE_STATUS: " + gl.getProgramParameter(program, gl.VALIDATE_STATUS) + "\n" + "gl.getError()" + gl.getError() + "\n" + "gl.getProgramInfoLog()" + gl.getProgramInfoLog(program));
}
gl.useProgram(program); // clean-up
gl.deleteShader(vertShader);
gl.deleteShader(fragShader);
return program;
}
|
javascript
|
{
"resource": ""
}
|
q22325
|
minify
|
train
|
function minify(src) {
// remove comments
src = src.replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm, "$1"); // Remove leading and trailing whitespace from lines
src = src.replace(/(\\n\s+)|(\s+\\n)/g, ""); // Remove line breaks
src = src.replace(/(\\r|\\n)+/g, ""); // Remove unnecessary whitespace
src = src.replace(/\s*([;,[\](){}\\\/\-+*|^&!=<>?~%])\s*/g, "$1");
return src;
}
|
javascript
|
{
"resource": ""
}
|
q22326
|
setEvent
|
train
|
function setEvent(event, pageX, pageY, clientX, clientY, pointerId) {
var width = 1;
var height = 1; // the original event object
this.event = event;
this.pageX = pageX || 0;
this.pageY = pageY || 0;
this.clientX = clientX || 0;
this.clientY = clientY || 0; // translate to local coordinates
me.input.globalToLocal(this.pageX, this.pageY, this.pos); // true if not originally a pointer event
this.isNormalized = !me.device.PointerEvent || me.device.PointerEvent && !(event instanceof window.PointerEvent);
if (event.type === "wheel") {
this.deltaMode = 1;
this.deltaX = event.deltaX;
this.deltaY = -1 / 40 * event.wheelDelta;
event.wheelDeltaX && (this.deltaX = -1 / 40 * event.wheelDeltaX);
} // could be 0, so test if defined
this.pointerId = typeof pointerId !== "undefined" ? pointerId : 1;
this.isPrimary = typeof event.isPrimary !== "undefined" ? event.isPrimary : true; // in case of touch events, button is not defined
this.button = event.button || 0;
this.type = event.type;
this.gameScreenX = this.pos.x;
this.gameScreenY = this.pos.y; // get the current screen to world offset
if (typeof me.game.viewport !== "undefined") {
me.game.viewport.localToWorld(this.gameScreenX, this.gameScreenY, viewportOffset);
}
/* Initialize the two coordinate space properties. */
this.gameWorldX = viewportOffset.x;
this.gameWorldY = viewportOffset.y; // get the pointer size
if (this.isNormalized === false) {
// native PointerEvent
width = event.width || 1;
height = event.height || 1;
} else if (typeof event.radiusX === "number") {
// TouchEvent
width = event.radiusX * 2 || 1;
height = event.radiusY * 2 || 1;
} // resize the pointer object accordingly
this.resize(width, height);
}
|
javascript
|
{
"resource": ""
}
|
q22327
|
normalizeEvent
|
train
|
function normalizeEvent(event) {
var pointer; // PointerEvent or standard Mouse event
if (me.device.TouchEvent && event.changedTouches) {
// iOS/Android Touch event
for (var i = 0, l = event.changedTouches.length; i < l; i++) {
var touchEvent = event.changedTouches[i];
pointer = T_POINTERS.pop();
pointer.setEvent(event, touchEvent.pageX, touchEvent.pageY, touchEvent.clientX, touchEvent.clientY, touchEvent.identifier);
normalizedEvents.push(pointer);
}
} else {
// Mouse or PointerEvent
pointer = T_POINTERS.pop();
pointer.setEvent(event, event.pageX, event.pageY, event.clientX, event.clientY, event.pointerId);
normalizedEvents.push(pointer);
} // if event.isPrimary is defined and false, return
if (event.isPrimary === false) {
return normalizedEvents;
} // else use the first entry to simulate mouse event
normalizedEvents[0].isPrimary = true;
Object.assign(api.pointer, normalizedEvents[0]);
return normalizedEvents;
}
|
javascript
|
{
"resource": ""
}
|
q22328
|
wiredXbox360NormalizeFn
|
train
|
function wiredXbox360NormalizeFn(value, axis, button) {
if (button === api.GAMEPAD.BUTTONS.L2 || button === api.GAMEPAD.BUTTONS.R2) {
return (value + 1) / 2;
}
return value;
}
|
javascript
|
{
"resource": ""
}
|
q22329
|
ouyaNormalizeFn
|
train
|
function ouyaNormalizeFn(value, axis, button) {
if (value > 0) {
if (button === api.GAMEPAD.BUTTONS.L2) {
// L2 is wonky; seems like the deadzone is around 20000
// (That's over 15% of the total range!)
value = Math.max(0, value - 20000) / 111070;
} else {
// Normalize [1..65536] => [0.0..0.5]
value = (value - 1) / 131070;
}
} else {
// Normalize [-65536..-1] => [0.5..1.0]
value = (65536 + value) / 131070 + 0.5;
}
return value;
}
|
javascript
|
{
"resource": ""
}
|
q22330
|
lighten
|
train
|
function lighten(scale) {
scale = me.Math.clamp(scale, 0, 1);
this.glArray[0] = me.Math.clamp(this.glArray[0] + (1 - this.glArray[0]) * scale, 0, 1);
this.glArray[1] = me.Math.clamp(this.glArray[1] + (1 - this.glArray[1]) * scale, 0, 1);
this.glArray[2] = me.Math.clamp(this.glArray[2] + (1 - this.glArray[2]) * scale, 0, 1);
return this;
}
|
javascript
|
{
"resource": ""
}
|
q22331
|
add
|
train
|
function add(props) {
Object.keys(props).forEach(function (key) {
if (isReserved(key)) {
return;
}
(function (prop) {
Object.defineProperty(api, prop, {
configurable: true,
enumerable: true,
/**
* @ignore
*/
get: function get() {
return data[prop];
},
/**
* @ignore
*/
set: function set(value) {
data[prop] = value;
if (me.device.localStorage === true) {
localStorage.setItem("me.save." + prop, JSON.stringify(value));
}
}
});
})(key); // Set default value for key
if (!(key in data)) {
api[key] = props[key];
}
}); // Save keys
if (me.device.localStorage === true) {
localStorage.setItem("me.save", JSON.stringify(Object.keys(data)));
}
}
|
javascript
|
{
"resource": ""
}
|
q22332
|
remove
|
train
|
function remove(key) {
if (!isReserved(key)) {
if (typeof data[key] !== "undefined") {
delete data[key];
if (me.device.localStorage === true) {
localStorage.removeItem("me.save." + key);
localStorage.setItem("me.save", JSON.stringify(Object.keys(data)));
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q22333
|
setTMXValue
|
train
|
function setTMXValue(name, type, value) {
var match;
if (typeof value !== "string") {
// Value is already normalized (e.g. with JSON maps)
return value;
}
switch (type) {
case "int":
case "float":
value = Number(value);
break;
case "bool":
value = value === "true";
break;
default:
// try to parse it anyway
if (!value || me.utils.string.isBoolean(value)) {
// if value not defined or boolean
value = value ? value === "true" : true;
} else if (me.utils.string.isNumeric(value)) {
// check if numeric
value = Number(value);
} else if (value.search(/^json:/i) === 0) {
// try to parse it
match = value.split(/^json:/i)[1];
try {
value = JSON.parse(match);
} catch (e) {
throw new Error("Unable to parse JSON: " + match);
}
} else if (value.search(/^eval:/i) === 0) {
// try to evaluate it
match = value.split(/^eval:/i)[1];
try {
// eslint-disable-next-line
value = eval(match);
} catch (e) {
throw new Error("Unable to evaluate: " + match);
}
} else if ((match = value.match(/^#([\da-fA-F])([\da-fA-F]{3})$/)) || (match = value.match(/^#([\da-fA-F]{2})([\da-fA-F]{6})$/))) {
value = "#" + match[2] + match[1];
} // normalize values
if (name.search(/^(ratio|anchorPoint)$/) === 0) {
// convert number to vector
if (typeof value === "number") {
value = {
"x": value,
"y": value
};
}
}
} // return the interpreted value
return value;
}
|
javascript
|
{
"resource": ""
}
|
q22334
|
parseTMXShapes
|
train
|
function parseTMXShapes() {
var i = 0;
var shapes = []; // add an ellipse shape
if (this.isEllipse === true) {
// ellipse coordinates are the center position, so set default to the corresonding radius
shapes.push(new me.Ellipse(this.width / 2, this.height / 2, this.width, this.height).rotate(this.rotation));
} // add a polygon
else if (this.isPolygon === true) {
shapes.push(new me.Polygon(0, 0, this.points).rotate(this.rotation));
} // add a polyline
else if (this.isPolyLine === true) {
var p = this.points;
var p1, p2;
var segments = p.length - 1;
for (i = 0; i < segments; i++) {
// clone the value before, as [i + 1]
// is reused later by the next segment
p1 = new me.Vector2d(p[i].x, p[i].y);
p2 = new me.Vector2d(p[i + 1].x, p[i + 1].y);
if (this.rotation !== 0) {
p1 = p1.rotate(this.rotation);
p2 = p2.rotate(this.rotation);
}
shapes.push(new me.Line(0, 0, [p1, p2]));
}
} // it's a rectangle, returns a polygon object anyway
else {
shapes.push(new me.Polygon(0, 0, [new me.Vector2d(), new me.Vector2d(this.width, 0), new me.Vector2d(this.width, this.height), new me.Vector2d(0, this.height)]).rotate(this.rotation));
} // Apply isometric projection
if (this.orientation === "isometric") {
for (i = 0; i < shapes.length; i++) {
shapes[i].toIso();
}
}
return shapes;
}
|
javascript
|
{
"resource": ""
}
|
q22335
|
createTransform
|
train
|
function createTransform() {
if (this.currentTransform === null) {
this.currentTransform = new me.Matrix2d();
} else {
// reset the matrix
this.currentTransform.identity();
}
if (this.flippedAD) {
// Use shearing to swap the X/Y axis
this.currentTransform.setTransform(0, 1, 0, 1, 0, 0, 0, 0, 1);
this.currentTransform.translate(0, this.height - this.width);
}
if (this.flippedX) {
this.currentTransform.translate(this.flippedAD ? 0 : this.width, this.flippedAD ? this.height : 0);
this.currentTransform.scaleX(-1);
}
if (this.flippedY) {
this.currentTransform.translate(this.flippedAD ? this.width : 0, this.flippedAD ? 0 : this.height);
this.currentTransform.scaleY(-1);
}
}
|
javascript
|
{
"resource": ""
}
|
q22336
|
getRenderable
|
train
|
function getRenderable(settings) {
var renderable;
var tileset = this.tileset;
if (tileset.animations.has(this.tileId)) {
var frames = [];
var frameId = [];
tileset.animations.get(this.tileId).frames.forEach(function (frame) {
frameId.push(frame.tileid);
frames.push({
name: "" + frame.tileid,
delay: frame.duration
});
});
renderable = tileset.texture.createAnimationFromName(frameId, settings);
renderable.addAnimation(this.tileId - tileset.firstgid, frames);
renderable.setCurrentAnimation(this.tileId - tileset.firstgid);
} else {
if (tileset.isCollection === true) {
var image = tileset.getTileImage(this.tileId);
renderable = new me.Sprite(0, 0, Object.assign({
image: image
}) //, settings)
);
renderable.anchorPoint.set(0, 0);
renderable.scale(settings.width / this.width, settings.height / this.height);
if (typeof settings.rotation !== "undefined") {
renderable.anchorPoint.set(0.5, 0.5);
renderable.currentTransform.rotate(settings.rotation);
renderable.currentTransform.translate(settings.width / 2, settings.height / 2); // TODO : move the rotation related code from TMXTiledMap to here (under)
settings.rotation = undefined;
}
} else {
renderable = tileset.texture.createSpriteFromName(this.tileId - tileset.firstgid, settings);
}
} // any H/V flipping to apply?
if (this.flippedX) {
renderable.currentTransform.scaleX(-1);
}
if (this.flippedY) {
renderable.currentTransform.scaleY(-1);
}
return renderable;
}
|
javascript
|
{
"resource": ""
}
|
q22337
|
update
|
train
|
function update(dt) {
var duration = 0,
now = me.timer.getTime(),
result = false;
if (this._lastUpdate !== now) {
this._lastUpdate = now;
this.animations.forEach(function (anim) {
anim.dt += dt;
duration = anim.cur.duration;
while (anim.dt >= duration) {
anim.dt -= duration;
anim.idx = (anim.idx + 1) % anim.frames.length;
anim.cur = anim.frames[anim.idx];
duration = anim.cur.duration;
result = true;
}
});
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q22338
|
canRender
|
train
|
function canRender(component) {
return this.cols === component.cols && this.rows === component.rows && this.tilewidth === component.tilewidth && this.tileheight === component.tileheight;
}
|
javascript
|
{
"resource": ""
}
|
q22339
|
initArray
|
train
|
function initArray(layer) {
// initialize the array
layer.layerData = new Array(layer.cols);
for (var x = 0; x < layer.cols; x++) {
layer.layerData[x] = new Array(layer.rows);
for (var y = 0; y < layer.rows; y++) {
layer.layerData[x][y] = null;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q22340
|
setLayerData
|
train
|
function setLayerData(layer, data) {
var idx = 0; // initialize the array
initArray(layer); // set everything
for (var y = 0; y < layer.rows; y++) {
for (var x = 0; x < layer.cols; x++) {
// get the value of the gid
var gid = data[idx++]; // fill the array
if (gid !== 0) {
// add a new tile to the layer
layer.setTile(x, y, gid);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q22341
|
getTileId
|
train
|
function getTileId(x, y) {
var tile = this.getTile(x, y);
return tile ? tile.tileId : null;
}
|
javascript
|
{
"resource": ""
}
|
q22342
|
setTile
|
train
|
function setTile(x, y, tileId) {
if (!this.tileset.contains(tileId)) {
// look for the corresponding tileset
this.tileset = this.tilesets.getTilesetByGid(tileId);
}
var tile = this.layerData[x][y] = new me.Tile(x, y, tileId, this.tileset); // draw the corresponding tile
if (this.preRender) {
this.renderer.drawTile(this.canvasRenderer, x, y, tile);
}
return tile;
}
|
javascript
|
{
"resource": ""
}
|
q22343
|
getRenderer
|
train
|
function getRenderer(layer) {
// first ensure a renderer is associated to this map
if (typeof this.renderer === "undefined" || !this.renderer.canRender(this)) {
this.renderer = getNewDefaultRenderer(this);
} // return a renderer for the given layer (if any)
if (typeof layer !== "undefined" && !this.renderer.canRender(layer)) {
return getNewDefaultRenderer(layer);
} // else return this renderer
return this.renderer;
}
|
javascript
|
{
"resource": ""
}
|
q22344
|
initEvents
|
train
|
function initEvents() {
var self = this;
/**
* @ignore
*/
this.mouseDown = function (e) {
this.translatePointerEvent(e, Event.DRAGSTART);
};
/**
* @ignore
*/
this.mouseUp = function (e) {
this.translatePointerEvent(e, Event.DRAGEND);
};
this.onPointerEvent("pointerdown", this, this.mouseDown.bind(this));
this.onPointerEvent("pointerup", this, this.mouseUp.bind(this));
this.onPointerEvent("pointercancel", this, this.mouseUp.bind(this));
Event.subscribe(Event.POINTERMOVE, this.dragMove.bind(this));
Event.subscribe(Event.DRAGSTART, function (e, draggable) {
if (draggable === self) {
self.dragStart(e);
}
});
Event.subscribe(Event.DRAGEND, function (e, draggable) {
if (draggable === self) {
self.dragEnd(e);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q22345
|
goTo
|
train
|
function goTo(level) {
this.gotolevel = level || this.nextlevel; // load a level
//console.log("going to : ", to);
if (this.fade && this.duration) {
if (!this.fading) {
this.fading = true;
me.game.viewport.fadeIn(this.fade, this.duration, this.onFadeComplete.bind(this));
}
} else {
me.levelDirector.loadLevel(this.gotolevel, this.getlevelSettings());
}
}
|
javascript
|
{
"resource": ""
}
|
q22346
|
train
|
function (duration, callback) {
this._flicker.duration = duration;
if (this._flicker.duration <= 0) {
this._flicker.isFlickering = false;
this._flicker.callback = null;
}
else if (!this._flicker.isFlickering) {
this._flicker.callback = callback;
this._flicker.isFlickering = true;
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q22347
|
train
|
function (/* event */) {
this.setRegion(this.unclicked_region);
// account for the different sprite size
this.pos.y -= this.unclicked_region.height - this.height;
this.height = this.unclicked_region.height;
// don't propagate the event
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q22348
|
train
|
function (selected) {
if (selected) {
this.setRegion(this.on_icon_region);
this.isSelected = true;
} else {
this.setRegion(this.off_icon_region);
this.isSelected = false;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22349
|
train
|
function (col, opaque) {
this.save();
this.resetTransform();
this.currentColor.copy(col);
if (opaque) {
this.compositor.clear();
}
else {
this.fillRect(0, 0, this.canvas.width, this.canvas.height);
}
this.restore();
}
|
javascript
|
{
"resource": ""
}
|
|
q22350
|
train
|
function (image, sx, sy, sw, sh, dx, dy, dw, dh) {
if (typeof sw === "undefined") {
sw = dw = image.width;
sh = dh = image.height;
dx = sx;
dy = sy;
sx = 0;
sy = 0;
}
else if (typeof dx === "undefined") {
dx = sx;
dy = sy;
dw = sw;
dh = sh;
sw = image.width;
sh = image.height;
sx = 0;
sy = 0;
}
if (this.settings.subPixel === false) {
// clamp to pixel grid
dx = ~~dx;
dy = ~~dy;
}
var key = sx + "," + sy + "," + sw + "," + sh;
this.compositor.addQuad(this.cache.get(image), key, dx, dy, dw, dh);
}
|
javascript
|
{
"resource": ""
}
|
|
q22351
|
train
|
function (x, y, width, height) {
var points = this._glPoints;
points[0].x = x;
points[0].y = y;
points[1].x = x + width;
points[1].y = y;
points[2].x = x + width;
points[2].y = y + height;
points[3].x = x;
points[3].y = y + height;
this.compositor.drawLine(points, 4);
}
|
javascript
|
{
"resource": ""
}
|
|
q22352
|
train
|
function () {
if (!this.visible) {
// add the debug panel to the game world
me.game.world.addChild(this, Infinity);
// register a mouse event for the checkboxes
me.input.registerPointerEvent("pointerdown", this, this.onClick.bind(this));
// mark it as visible
this.visible = true;
// force repaint
me.game.repaint();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22353
|
train
|
function () {
if (this.visible) {
// release the mouse event for the checkboxes
me.input.releasePointerEvent("pointerdown", this);
// remove the debug panel from the game world
me.game.world.removeChild(this, true);
// mark it as invisible
this.visible = false;
// force repaint
me.game.repaint();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22354
|
train
|
function () {
var self = this;
// add all defined cameras
this.settings.cameras.forEach(function(camera) {
self.cameras.set(camera.name, camera);
});
// empty or no default camera
if (this.cameras.has("default") === false) {
if (typeof default_camera === "undefined") {
var width = me.video.renderer.getWidth();
var height = me.video.renderer.getHeight();
// new default camera instance
default_camera = new me.Camera2d(0, 0, width, height);
}
this.cameras.set("default", default_camera);
}
// reset the game manager
me.game.reset();
// call the onReset Function
this.onResetEvent.apply(this, arguments);
}
|
javascript
|
{
"resource": ""
}
|
|
q22355
|
train
|
function (m) {
var bounds = this.getBounds();
this.currentTransform.multiply(m);
bounds.setPoints(bounds.transform(m).points);
bounds.pos.setV(this.pos);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q22356
|
train
|
function (target) {
var a = this.getBounds();
var ax, ay;
if (target instanceof me.Renderable) {
var b = target.getBounds();
ax = b.centerX - a.centerX;
ay = b.centerY - a.centerY;
} else { // vector object
ax = target.x - a.centerX;
ay = target.y - a.centerY;
}
return Math.atan2(ay, ax);
}
|
javascript
|
{
"resource": ""
}
|
|
q22357
|
train
|
function (target) {
var a = this.getBounds();
var dx, dy;
if (target instanceof me.Renderable) {
var b = target.getBounds();
dx = a.centerX - b.centerX;
dy = a.centerY - b.centerY;
} else { // vector object
dx = a.centerX - target.x;
dy = a.centerY - target.y;
}
return Math.sqrt(dx * dx + dy * dy);
}
|
javascript
|
{
"resource": ""
}
|
|
q22358
|
train
|
function (target) {
var position;
if (target instanceof me.Renderable) {
position = target.pos;
} else {
position = target;
}
var angle = this.angleTo(position);
this.rotate(angle);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q22359
|
train
|
function (b) {
b = b.val;
var a = this.val,
a0 = a[0],
a1 = a[1],
a3 = a[3],
a4 = a[4],
b0 = b[0],
b1 = b[1],
b3 = b[3],
b4 = b[4],
b6 = b[6],
b7 = b[7];
a[0] = a0 * b0 + a3 * b1;
a[1] = a1 * b0 + a4 * b1;
a[3] = a0 * b3 + a3 * b4;
a[4] = a1 * b3 + a4 * b4;
a[6] += a0 * b6 + a3 * b7;
a[7] += a1 * b6 + a4 * b7;
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q22360
|
train
|
function () {
var val = this.val;
var a = val[ 0 ], b = val[ 1 ], c = val[ 2 ],
d = val[ 3 ], e = val[ 4 ], f = val[ 5 ],
g = val[ 6 ], h = val[ 7 ], i = val[ 8 ];
var ta = i * e - f * h,
td = f * g - i * d,
tg = h * d - e * g;
var n = a * ta + b * td + c * tg;
val[ 0 ] = ta / n;
val[ 1 ] = ( c * h - i * b ) / n;
val[ 2 ] = ( f * b - c * e ) / n;
val[ 3 ] = td / n;
val[ 4 ] = ( i * a - c * g ) / n;
val[ 5 ] = ( c * d - f * a ) / n;
val[ 6 ] = tg / n;
val[ 7 ] = ( b * g - h * a ) / n;
val[ 8 ] = ( e * a - b * d ) / n;
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q22361
|
train
|
function (v) {
var a = this.val,
x = v.x,
y = v.y;
v.x = x * a[0] + y * a[3] + a[6];
v.y = x * a[1] + y * a[4] + a[7];
return v;
}
|
javascript
|
{
"resource": ""
}
|
|
q22362
|
train
|
function (x, y) {
var a = this.val,
_x = x,
_y = typeof(y) === "undefined" ? _x : y;
a[0] *= _x;
a[1] *= _x;
a[3] *= _y;
a[4] *= _y;
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q22363
|
train
|
function (x, y) {
var a = this.val;
a[6] += a[0] * x + a[3] * y;
a[7] += a[1] * x + a[4] * y;
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q22364
|
train
|
function (width, height) {
if (width !== this.backBufferCanvas.width || height !== this.backBufferCanvas.height) {
this.canvas.width = this.backBufferCanvas.width = width;
this.canvas.height = this.backBufferCanvas.height = height;
this.currentScissor[0] = 0;
this.currentScissor[1] = 0;
this.currentScissor[2] = width;
this.currentScissor[3] = height;
// publish the corresponding event
me.event.publish(me.event.CANVAS_ONRESIZE, [ width, height ]);
}
this.updateBounds();
}
|
javascript
|
{
"resource": ""
}
|
|
q22365
|
train
|
function (x, y) {
var _x = this.pos.x;
var _y = this.pos.y;
this.pos.x = me.Math.clamp(
x,
this.bounds.pos.x,
this.bounds.width - this.width
);
this.pos.y = me.Math.clamp(
y,
this.bounds.pos.y,
this.bounds.height - this.height
);
//publish the VIEWPORT_ONCHANGE event if necessary
if (_x !== this.pos.x || _y !== this.pos.y) {
me.event.publish(me.event.VIEWPORT_ONCHANGE, [this.pos]);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22366
|
train
|
function (target) {
var bounds = target.getBounds();
this.moveTo(
target.pos.x + bounds.pos.x + (bounds.width / 2),
target.pos.y + bounds.pos.y + (bounds.height / 2)
);
}
|
javascript
|
{
"resource": ""
}
|
|
q22367
|
train
|
function (obj, floating) {
if (floating === true || obj.floating === true) {
// check against screen coordinates
return me.video.renderer.overlaps(obj.getBounds());
} else {
// check if within the current camera
return obj.getBounds().overlaps(this);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22368
|
train
|
function (event) {
var tile = this.refLayer.getTile(event.gameWorldX, event.gameWorldY);
if (tile && tile !== this.currentTile) {
// get the tile x/y world isometric coordinates
this.refLayer.getRenderer().tileToPixelCoords(tile.col, tile.row, this.diamondShape.pos);
// convert thhe diamon shape pos to floating coordinates
me.game.viewport.worldToLocal(
this.diamondShape.pos.x,
this.diamondShape.pos.y,
this.diamondShape.pos
);
// store the current tile
this.currentTile = tile;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q22369
|
train
|
function (obj) {
var tileX = obj.x / this.hTilewidth;
var tileY = obj.y / this.tileheight;
var isoPos = me.pool.pull("me.Vector2d");
this.tileToPixelCoords(tileX, tileY, isoPos);
obj.x = isoPos.x;
obj.y = isoPos.y;
me.pool.push(isoPos);
}
|
javascript
|
{
"resource": ""
}
|
|
q22370
|
train
|
function (x, y) {
if (this.containsPoint(x, y)) {
var renderer = this.renderer;
var tile = null;
var coord = renderer.pixelToTileCoords(x, y, me.pool.pull("me.Vector2d"));
if ((coord.x >= 0 && coord.x < renderer.cols) && ( coord.y >= 0 && coord.y < renderer.rows)) {
tile = this.layerData[~~coord.x][~~coord.y];
}
me.pool.push(coord);
}
return tile;
}
|
javascript
|
{
"resource": ""
}
|
|
q22371
|
train
|
function (x, y) {
// clearing tile
this.layerData[x][y] = null;
// erase the corresponding area in the canvas
if (this.preRender) {
this.canvasRenderer.clearRect(x * this.tilewidth, y * this.tileheight, this.tilewidth, this.tileheight);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22372
|
train
|
function (dt) {
if (this.isAnimated) {
var result = false;
for (var i = 0; i < this.animatedTilesets.length; i++) {
result = this.animatedTilesets[i].update(dt) || result;
}
return result;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q22373
|
train
|
function (renderer, rect) {
// use the offscreen canvas
if (this.preRender) {
var width = Math.min(rect.width, this.width);
var height = Math.min(rect.height, this.height);
// draw using the cached canvas
renderer.drawImage(
this.canvasRenderer.getCanvas(),
rect.pos.x, rect.pos.y, // sx,sy
width, height, // sw,sh
rect.pos.x, rect.pos.y, // dx,dy
width, height // dw,dh
);
}
// dynamically render the layer
else {
// draw the layer
this.renderer.drawTileLayer(renderer, this, rect);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22374
|
train
|
function () {
return new me.Ellipse(
this.pos.x,
this.pos.y,
this.radiusV.x * 2,
this.radiusV.y * 2
);
}
|
javascript
|
{
"resource": ""
}
|
|
q22375
|
train
|
function (x, y) {
if (x - this.pos.x < this.width / 2) {
if (this.cursors.left === false) {
me.input.triggerKeyEvent(me.input.KEY.LEFT, true);
this.cursors.left = true;
this.joypad_offset.x = -((this.width / 2 - (x - this.pos.x)) % this.pad.width / 4);
}
// release the right key if it was pressed
if (this.cursors.right === true) {
me.input.triggerKeyEvent(me.input.KEY.RIGHT, false);
this.cursors.right = false;
}
}
if (x - this.pos.x > this.width / 2) {
if (this.cursors.right === false) {
me.input.triggerKeyEvent(me.input.KEY.RIGHT, true);
this.cursors.right = true;
this.joypad_offset.x = +(((x - this.pos.x) - this.width / 2) % this.pad.width / 4);
}
// release the left key is it was pressed
if (this.cursors.left === true) {
me.input.triggerKeyEvent(me.input.KEY.LEFT, false);
this.cursors.left = false;
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22376
|
train
|
function (event) {
this.setOpacity(0.25);
if (this.cursors.left === true) {
me.input.triggerKeyEvent(me.input.KEY.LEFT, false);
this.cursors.left = false;
}
if (this.cursors.right === true) {
me.input.triggerKeyEvent(me.input.KEY.RIGHT, false);
this.cursors.right = false;
}
this.joypad_offset.set(0, 0);
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q22377
|
train
|
function (renderer) {
// call the super constructor
this._super(me.GUI_Object, "draw", [ renderer ]);
this.pad.pos.setV(this.pos).add(this.relative).add(this.joypad_offset);
this.pad.draw(renderer);
}
|
javascript
|
{
"resource": ""
}
|
|
q22378
|
train
|
function() {
if (this.isOut === true) {
this.isOut = false;
// set touch animation
this.setCurrentAnimation("touch", this.hide.bind(this));
// make it flicker
this.flicker(750);
// play ow FX
me.audio.play("ow");
// add some points
game.data.score += 100;
if (game.data.hiscore < game.data.score) {
// i could save direclty to me.save
// but that allows me to only have one
// simple HUD Score Object
game.data.hiscore = game.data.score;
// save to local storage
me.save.hiscore = game.data.hiscore;
}
// stop propagating the event
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22379
|
train
|
function() {
var finalpos = this.initialPos - 140;
this.displayTween = me.pool.pull("me.Tween", this.pos).to({y: finalpos }, 200);
this.displayTween.easing(me.Tween.Easing.Quadratic.Out);
this.displayTween.onComplete(this.onDisplayed.bind(this));
this.displayTween.start();
// the mole is visible
this.isVisible = true;
}
|
javascript
|
{
"resource": ""
}
|
|
q22380
|
train
|
function() {
var finalpos = this.initialPos;
this.displayTween = me.pool.pull("me.Tween", this.pos).to({y: finalpos }, 200);
this.displayTween.easing(me.Tween.Easing.Quadratic.In);
this.displayTween.onComplete(this.onHidden.bind(this));
this.displayTween.start();
}
|
javascript
|
{
"resource": ""
}
|
|
q22381
|
train
|
function ( dt )
{
if (this.isVisible) {
// call the super function to manage animation
this._super(me.Sprite, "update", [dt] );
// hide the mode after 1/2 sec
if (this.isOut===true) {
this.timer += dt;
if ((this.timer) >= 500) {
this.isOut = false;
// set default one
this.setCurrentAnimation("laugh");
this.hide();
// play laugh FX
//me.audio.play("laugh");
// decrease score by 25 pts
game.data.score -= 25;
if (game.data.score < 0) {
game.data.score = 0;
}
}
return true;
}
}
return this.isVisible;
}
|
javascript
|
{
"resource": ""
}
|
|
q22382
|
train
|
function (e, keyCode, mouseButton) {
keyCode = keyCode || e.keyCode || e.button;
var action = keyBindings[keyCode];
// publish a message for keydown event
me.event.publish(me.event.KEYDOWN, [
action,
keyCode,
action ? !keyLocked[action] : true
]);
if (action) {
if (!keyLocked[action]) {
var trigger = (typeof mouseButton !== "undefined") ? mouseButton : keyCode;
if (!keyRefs[action][trigger]) {
keyStatus[action]++;
keyRefs[action][trigger] = true;
}
}
// prevent event propagation
if (preventDefaultForKeys[keyCode] && (typeof e.preventDefault === "function")) {
// "fake" events generated through triggerKeyEvent do not have a preventDefault fn
return e.preventDefault();
}
else {
return true;
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
|
q22383
|
train
|
function () {
// cancel any sort operation
if (this.pendingSort) {
clearTimeout(this.pendingSort);
this.pendingSort = null;
}
// delete all children
for (var i = this.children.length, obj; i >= 0; (obj = this.children[--i])) {
// don't remove it if a persistent object
if (obj && !obj.isPersistent) {
this.removeChildNow(obj);
}
}
if (typeof this.currentTransform !== "undefined") {
// just reset some variables
this.currentTransform.identity();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22384
|
train
|
function (a, b) {
if (!b.pos || !a.pos) {
return (a.pos ? -Infinity : Infinity);
}
var result = b.pos.z - a.pos.z;
return (result ? result : (b.pos.x - a.pos.x));
}
|
javascript
|
{
"resource": ""
}
|
|
q22385
|
train
|
function (a, b) {
if (!b.pos || !a.pos) {
return (a.pos ? -Infinity : Infinity);
}
var result = b.pos.z - a.pos.z;
return (result ? result : (b.pos.y - a.pos.y));
}
|
javascript
|
{
"resource": ""
}
|
|
q22386
|
train
|
function (renderer) {
var viewport = me.game.viewport,
width = this.imagewidth,
height = this.imageheight,
bw = viewport.bounds.width,
bh = viewport.bounds.height,
ax = this.anchorPoint.x,
ay = this.anchorPoint.y,
x = this.pos.x,
y = this.pos.y;
if (this.ratio.x === this.ratio.y === 0) {
x = x + ax * (bw - width);
y = y + ay * (bh - height);
}
renderer.translate(x, y);
renderer.drawPattern(
this._pattern,
0,
0,
viewport.width * 2,
viewport.height * 2
);
}
|
javascript
|
{
"resource": ""
}
|
|
q22387
|
train
|
function (e) {
// save a reference to this to use in the timeout
var self = this;
// call the super function
this._super(me.DroptargetEntity, "draw", [e]);
// indicate a succesful drop
this.color = "green";
// set the color back to red after a second
window.setTimeout(function () {
self.color = "red";
}, 1000);
}
|
javascript
|
{
"resource": ""
}
|
|
q22388
|
addModulesToPackageJson
|
train
|
function addModulesToPackageJson(externalModules, packageJson, pathToPackageRoot) {
_.forEach(externalModules, externalModule => {
const splitModule = _.split(externalModule, '@');
// If we have a scoped module we have to re-add the @
if (_.startsWith(externalModule, '@')) {
splitModule.splice(0, 1);
splitModule[0] = '@' + splitModule[0];
}
let moduleVersion = _.join(_.tail(splitModule), '@');
// We have to rebase file references to the target package.json
moduleVersion = rebaseFileReferences(pathToPackageRoot, moduleVersion);
packageJson.dependencies = packageJson.dependencies || {};
packageJson.dependencies[_.first(splitModule)] = moduleVersion;
});
}
|
javascript
|
{
"resource": ""
}
|
q22389
|
removeExcludedModules
|
train
|
function removeExcludedModules(modules, packageForceExcludes, log) {
const excludedModules = _.remove(modules, externalModule => { // eslint-disable-line lodash/prefer-immutable-method
const splitModule = _.split(externalModule, '@');
// If we have a scoped module we have to re-add the @
if (_.startsWith(externalModule, '@')) {
splitModule.splice(0, 1);
splitModule[0] = '@' + splitModule[0];
}
const moduleName = _.first(splitModule);
return _.includes(packageForceExcludes, moduleName);
});
if (log && !_.isEmpty(excludedModules)) {
this.serverless.cli.log(`Excluding external modules: ${_.join(excludedModules, ', ')}`);
}
}
|
javascript
|
{
"resource": ""
}
|
q22390
|
getProdModules
|
train
|
function getProdModules(externalModules, packagePath, dependencyGraph, forceExcludes) {
const packageJsonPath = path.join(process.cwd(), packagePath);
const packageJson = require(packageJsonPath);
const prodModules = [];
// only process the module stated in dependencies section
if (!packageJson.dependencies) {
return [];
}
// Get versions of all transient modules
_.forEach(externalModules, module => {
let moduleVersion = packageJson.dependencies[module.external];
if (moduleVersion) {
prodModules.push(`${module.external}@${moduleVersion}`);
// Check if the module has any peer dependencies and include them too
try {
const modulePackagePath = path.join(
path.dirname(path.join(process.cwd(), packagePath)),
'node_modules',
module.external,
'package.json'
);
const peerDependencies = require(modulePackagePath).peerDependencies;
if (!_.isEmpty(peerDependencies)) {
this.options.verbose && this.serverless.cli.log(`Adding explicit peers for dependency ${module.external}`);
const peerModules = getProdModules.call(this, _.map(peerDependencies, (value, key) => ({ external: key })), packagePath, dependencyGraph, forceExcludes);
Array.prototype.push.apply(prodModules, peerModules);
}
} catch (e) {
this.serverless.cli.log(`WARNING: Could not check for peer dependencies of ${module.external}`);
}
} else {
if (!packageJson.devDependencies || !packageJson.devDependencies[module.external]) {
// Add transient dependencies if they appear not in the service's dev dependencies
const originInfo = _.get(dependencyGraph, 'dependencies', {})[module.origin] || {};
moduleVersion = _.get(_.get(originInfo, 'dependencies', {})[module.external], 'version');
if (!moduleVersion) {
this.serverless.cli.log(`WARNING: Could not determine version of module ${module.external}`);
}
prodModules.push(moduleVersion ? `${module.external}@${moduleVersion}` : module.external);
} else if (packageJson.devDependencies && packageJson.devDependencies[module.external] && !_.includes(forceExcludes, module.external)) {
// To minimize the chance of breaking setups we whitelist packages available on AWS here. These are due to the previously missing check
// most likely set in devDependencies and should not lead to an error now.
const ignoredDevDependencies = ['aws-sdk'];
if (!_.includes(ignoredDevDependencies, module.external)) {
// Runtime dependency found in devDependencies but not forcefully excluded
this.serverless.cli.log(`ERROR: Runtime dependency '${module.external}' found in devDependencies. Move it to dependencies or use forceExclude to explicitly exclude it.`);
throw new this.serverless.classes.Error(`Serverless-webpack dependency error: ${module.external}.`);
}
this.options.verbose && this.serverless.cli.log(`INFO: Runtime dependency '${module.external}' found in devDependencies. It has been excluded automatically.`);
}
}
});
return prodModules;
}
|
javascript
|
{
"resource": ""
}
|
q22391
|
findExternalOrigin
|
train
|
function findExternalOrigin(issuer) {
if (!_.isNil(issuer) && _.startsWith(issuer.rawRequest, './')) {
return findExternalOrigin(issuer.issuer);
}
return issuer;
}
|
javascript
|
{
"resource": ""
}
|
q22392
|
purgeCache
|
train
|
function purgeCache(moduleName) {
return searchAndProcessCache(moduleName, function (mod) {
delete require.cache[mod.id];
})
.then(() => {
_.forEach(_.keys(module.constructor._pathCache), function(cacheKey) {
if (cacheKey.indexOf(moduleName)>0) {
delete module.constructor._pathCache[cacheKey];
}
});
return BbPromise.resolve();
});
}
|
javascript
|
{
"resource": ""
}
|
q22393
|
getBlock
|
train
|
function getBlock(control) {
var block = control.parentNode;
while (block.getAttribute("role") !== "tablist") {
block = block.parentNode;
}
return block;
}
|
javascript
|
{
"resource": ""
}
|
q22394
|
dashify
|
train
|
function dashify( prop ) {
if (!prop) {
return '';
}
// Replace upper case with dash-lowercase,
// then fix ms- prefixes because they're not capitalized.
return prop.replace(/([A-Z])/g, function( str, m1 ) {
return '-' + m1.toLowerCase();
}).replace(/^ms-/,'-ms-');
}
|
javascript
|
{
"resource": ""
}
|
q22395
|
train
|
function( element, options ) {
options = options || {};
$.extend( this, Shuffle.options, options, Shuffle.settings );
this.$el = $(element);
this.element = element;
this.unique = 'shuffle_' + id++;
this._fire( Shuffle.EventType.LOADING );
this._init();
// Dispatch the done event asynchronously so that people can bind to it after
// Shuffle has been initialized.
defer(function() {
this.initialized = true;
this._fire( Shuffle.EventType.DONE );
}, this, 16);
}
|
javascript
|
{
"resource": ""
}
|
|
q22396
|
handleTransitionEnd
|
train
|
function handleTransitionEnd( evt ) {
// Make sure this event handler has not bubbled up from a child.
if ( evt.target === evt.currentTarget ) {
$( evt.target ).off( TRANSITIONEND, handleTransitionEnd );
callback();
}
}
|
javascript
|
{
"resource": ""
}
|
q22397
|
train
|
function (layers) {
var id, parent;
// Assumes layers is an Array or an Object whose prototype is non-enumerable.
for (id in layers) {
// Flag parent clusters' icon as "dirty", all the way up.
// Dumb process that flags multiple times upper parents, but still
// much more efficient than trying to be smart and make short lists,
// at least in the case of a hierarchy following a power law:
// http://jsperf.com/flag-nodes-in-power-hierarchy/2
parent = layers[id].__parent;
while (parent) {
parent._iconNeedsUpdate = true;
parent = parent.__parent;
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22398
|
train
|
function (layers) {
var id, layer;
for (id in layers) {
layer = layers[id];
// Make sure we do not override markers that do not belong to THIS group.
if (this.hasLayer(layer)) {
// Need to re-create the icon first, then re-draw the marker.
layer.setIcon(this._overrideMarkerIcon(layer));
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22399
|
train
|
function (options, directlyRefreshClusters) {
var icon = this.options.icon;
L.setOptions(icon, options);
this.setIcon(icon);
// Shortcut to refresh the associated MCG clusters right away.
// To be used when refreshing a single marker.
// Otherwise, better use MCG.refreshClusters() once at the end with
// the list of modified markers.
if (directlyRefreshClusters && this.__parent) {
this.__parent._group.refreshClusters(this);
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.