_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q26400 | train | function () {
var activeObject = this.getActiveGroup() || this.getActiveObject();
if (activeObject) {
this.fire('before:selection:cleared', { target: activeObject });
}
this.deactivateAll();
if (activeObject) {
this.fire('selection:cleared');
}
return this;
} | javascript | {
"resource": ""
} | |
q26401 | train | function (object, callbacks) {
callbacks = callbacks || { };
var empty = function() { },
onComplete = callbacks.onComplete || empty,
onChange = callbacks.onChange || empty,
_this = this;
fabric.util.animate({
startValue: object.get('left'),
endValue: this.getCenter().left,
duration: this.FX_DURATION,
onChange: function(value) {
object.set('left', value);
_this.renderAll();
onChange();
},
onComplete: function() {
object.setCoords();
onComplete();
}
});
return this;
} | javascript | {
"resource": ""
} | |
q26402 | train | function (callback) {
var data = JSON.stringify(this);
this.cloneWithoutData(function(clone) {
clone.loadFromJSON(data, function() {
callback && callback(clone);
});
});
} | javascript | {
"resource": ""
} | |
q26403 | train | function() {
var NUM_FRACTION_DIGITS = fabric.Object.NUM_FRACTION_DIGITS;
var object = {
type: this.type,
left: toFixed(this.left, NUM_FRACTION_DIGITS),
top: toFixed(this.top, NUM_FRACTION_DIGITS),
width: toFixed(this.width, NUM_FRACTION_DIGITS),
height: toFixed(this.height, NUM_FRACTION_DIGITS),
fill: (this.fill && this.fill.toObject) ? this.fill.toObject() : this.fill,
overlayFill: this.overlayFill,
stroke: this.stroke,
strokeWidth: this.strokeWidth,
strokeDashArray: this.strokeDashArray,
scaleX: toFixed(this.scaleX, NUM_FRACTION_DIGITS),
scaleY: toFixed(this.scaleY, NUM_FRACTION_DIGITS),
angle: toFixed(this.getAngle(), NUM_FRACTION_DIGITS),
flipX: this.flipX,
flipY: this.flipY,
opacity: toFixed(this.opacity, NUM_FRACTION_DIGITS),
selectable: this.selectable,
hasControls: this.hasControls,
hasBorders: this.hasBorders,
hasRotatingPoint: this.hasRotatingPoint,
transparentCorners: this.transparentCorners,
perPixelTargetFind: this.perPixelTargetFind
};
if (!this.includeDefaultValues) {
object = this._removeDefaultValues(object);
}
return object;
} | javascript | {
"resource": ""
} | |
q26404 | train | function() {
return [
"stroke: ", (this.stroke ? this.stroke : 'none'), "; ",
"stroke-width: ", (this.strokeWidth ? this.strokeWidth : '0'), "; ",
"stroke-dasharray: ", (this.strokeDashArray ? this.strokeDashArray.join(' ') : "; "),
"fill: ", (this.fill ? this.fill : 'none'), "; ",
"opacity: ", (this.opacity ? this.opacity : '1'), ";"
].join("");
} | javascript | {
"resource": ""
} | |
q26405 | train | function() {
var angle = this.getAngle();
return [
"translate(", toFixed(this.left, 2), " ", toFixed(this.top, 2), ")",
angle !== 0 ? (" rotate(" + toFixed(angle, 2) + ")") : '',
(this.scaleX === 1 && this.scaleY === 1) ? '' : (" scale(" + toFixed(this.scaleX, 2) + " " + toFixed(this.scaleY, 2) + ")")
].join('');
} | javascript | {
"resource": ""
} | |
q26406 | train | function(key, value) {
if (typeof key === 'object') {
for (var prop in key) {
this._set(prop, key[prop]);
}
}
else {
if (typeof value === 'function') {
this._set(key, value(this.get(key)));
}
else {
this._set(key, value);
}
}
return this;
} | javascript | {
"resource": ""
} | |
q26407 | train | function() {
this.oCoords || this.setCoords();
var xCoords = [this.oCoords.tl.x, this.oCoords.tr.x, this.oCoords.br.x, this.oCoords.bl.x];
var minX = fabric.util.array.min(xCoords);
var maxX = fabric.util.array.max(xCoords);
return Math.abs(minX - maxX);
} | javascript | {
"resource": ""
} | |
q26408 | train | function() {
this.oCoords || this.setCoords();
var yCoords = [this.oCoords.tl.y, this.oCoords.tr.y, this.oCoords.br.y, this.oCoords.bl.y];
var minY = fabric.util.array.min(yCoords);
var maxY = fabric.util.array.max(yCoords);
return Math.abs(minY - maxY);
} | javascript | {
"resource": ""
} | |
q26409 | train | function(options) {
if (this.constructor.fromObject) {
return this.constructor.fromObject(this.toObject(), options);
}
return new fabric.Object(this.toObject());
} | javascript | {
"resource": ""
} | |
q26410 | train | function(callback) {
if (fabric.Image) {
var i = new Image();
/** @ignore */
i.onload = function() {
if (callback) {
callback(new fabric.Image(i), orig);
}
i = i.onload = null;
};
var orig = {
angle: this.get('angle'),
flipX: this.get('flipX'),
flipY: this.get('flipY')
};
// normalize angle
this.set('angle', 0).set('flipX', false).set('flipY', false);
this.toDataURL(function(dataURL) {
i.src = dataURL;
});
}
return this;
} | javascript | {
"resource": ""
} | |
q26411 | train | function(callback) {
var el = fabric.document.createElement('canvas');
if (!el.getContext && typeof G_vmlCanvasManager != 'undefined') {
G_vmlCanvasManager.initElement(el);
}
el.width = this.getBoundingRectWidth();
el.height = this.getBoundingRectHeight();
fabric.util.wrapElement(el, 'div');
var canvas = new fabric.Canvas(el);
canvas.backgroundColor = 'transparent';
canvas.renderAll();
if (this.constructor.async) {
this.clone(proceed);
}
else {
proceed(this.clone());
}
function proceed(clone) {
clone.left = el.width / 2;
clone.top = el.height / 2;
clone.setActive(false);
canvas.add(clone);
var data = canvas.toDataURL('png');
canvas.dispose();
canvas = clone = null;
callback && callback(data);
}
} | javascript | {
"resource": ""
} | |
q26412 | train | function(selectionTL, selectionBR) {
var oCoords = this.oCoords,
tl = new fabric.Point(oCoords.tl.x, oCoords.tl.y),
tr = new fabric.Point(oCoords.tr.x, oCoords.tr.y),
bl = new fabric.Point(oCoords.bl.x, oCoords.bl.y),
br = new fabric.Point(oCoords.br.x, oCoords.br.y);
var intersection = fabric.Intersection.intersectPolygonRectangle(
[tl, tr, br, bl],
selectionTL,
selectionBR
);
return (intersection.status === 'Intersection');
} | javascript | {
"resource": ""
} | |
q26413 | train | function(other) {
// extracts coords
function getCoords(oCoords) {
return {
tl: new fabric.Point(oCoords.tl.x, oCoords.tl.y),
tr: new fabric.Point(oCoords.tr.x, oCoords.tr.y),
bl: new fabric.Point(oCoords.bl.x, oCoords.bl.y),
br: new fabric.Point(oCoords.br.x, oCoords.br.y)
}
}
var thisCoords = getCoords(this.oCoords),
otherCoords = getCoords(other.oCoords);
var intersection = fabric.Intersection.intersectPolygonPolygon(
[thisCoords.tl, thisCoords.tr, thisCoords.br, thisCoords.bl],
[otherCoords.tl, otherCoords.tr, otherCoords.br, otherCoords.bl]
);
return (intersection.status === 'Intersection');
} | javascript | {
"resource": ""
} | |
q26414 | train | function(selectionTL, selectionBR) {
var oCoords = this.oCoords,
tl = new fabric.Point(oCoords.tl.x, oCoords.tl.y),
tr = new fabric.Point(oCoords.tr.x, oCoords.tr.y),
bl = new fabric.Point(oCoords.bl.x, oCoords.bl.y),
br = new fabric.Point(oCoords.br.x, oCoords.br.y);
return tl.x > selectionTL.x
&& tr.x < selectionBR.x
&& tl.y > selectionTL.y
&& bl.y < selectionBR.y;
} | javascript | {
"resource": ""
} | |
q26415 | train | function(e, offset) {
if (!this.hasControls || !this.active) return false;
var pointer = getPointer(e),
ex = pointer.x - offset.left,
ey = pointer.y - offset.top,
xpoints,
lines;
for (var i in this.oCoords) {
if (i === 'mtr' && !this.hasRotatingPoint) {
continue;
}
if (this.lockUniScaling && (i === 'mt' || i === 'mr' || i === 'mb' || i === 'ml')) {
continue;
}
lines = this._getImageLines(this.oCoords[i].corner, i);
// debugging
// canvas.contextTop.fillRect(lines.bottomline.d.x, lines.bottomline.d.y, 2, 2);
// canvas.contextTop.fillRect(lines.bottomline.o.x, lines.bottomline.o.y, 2, 2);
// canvas.contextTop.fillRect(lines.leftline.d.x, lines.leftline.d.y, 2, 2);
// canvas.contextTop.fillRect(lines.leftline.o.x, lines.leftline.o.y, 2, 2);
// canvas.contextTop.fillRect(lines.topline.d.x, lines.topline.d.y, 2, 2);
// canvas.contextTop.fillRect(lines.topline.o.x, lines.topline.o.y, 2, 2);
// canvas.contextTop.fillRect(lines.rightline.d.x, lines.rightline.d.y, 2, 2);
// canvas.contextTop.fillRect(lines.rightline.o.x, lines.rightline.o.y, 2, 2);
xpoints = this._findCrossPoints(ex, ey, lines);
if (xpoints % 2 == 1 && xpoints != 0) {
this.__corner = i;
return i;
}
}
return false;
} | javascript | {
"resource": ""
} | |
q26416 | train | function(ex, ey, oCoords) {
var b1, b2, a1, a2, xi, yi,
xcount = 0,
iLine;
for (var lineKey in oCoords) {
iLine = oCoords[lineKey];
// optimisation 1: line below dot. no cross
if ((iLine.o.y < ey) && (iLine.d.y < ey)) {
continue;
}
// optimisation 2: line above dot. no cross
if ((iLine.o.y >= ey) && (iLine.d.y >= ey)) {
continue;
}
// optimisation 3: vertical line case
if ((iLine.o.x == iLine.d.x) && (iLine.o.x >= ex)) {
xi = iLine.o.x;
yi = ey;
}
// calculate the intersection point
else {
b1 = 0;
b2 = (iLine.d.y-iLine.o.y)/(iLine.d.x-iLine.o.x);
a1 = ey-b1*ex;
a2 = iLine.o.y-b2*iLine.o.x;
xi = - (a1-a2)/(b1-b2);
yi = a1+b1*xi;
}
// dont count xi < ex cases
if (xi >= ex) {
xcount += 1;
}
// optimisation 4: specific for square images
if (xcount == 2) {
break;
}
}
return xcount;
} | javascript | {
"resource": ""
} | |
q26417 | train | function(oCoords, i) {
return {
topline: {
o: oCoords.tl,
d: oCoords.tr
},
rightline: {
o: oCoords.tr,
d: oCoords.br
},
bottomline: {
o: oCoords.br,
d: oCoords.bl
},
leftline: {
o: oCoords.bl,
d: oCoords.tl
}
}
} | javascript | {
"resource": ""
} | |
q26418 | train | function(parsedAttributes) {
if (parsedAttributes.left) {
this.set('left', parsedAttributes.left + this.getWidth() / 2);
}
this.set('x', parsedAttributes.left || 0);
if (parsedAttributes.top) {
this.set('top', parsedAttributes.top + this.getHeight() / 2);
}
this.set('y', parsedAttributes.top || 0);
return this;
} | javascript | {
"resource": ""
} | |
q26419 | train | function(ctx, noTransform) {
ctx.save();
var m = this.transformMatrix;
if (m) {
ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
}
if (!noTransform) {
this.transform(ctx);
}
// ctx.globalCompositeOperation = this.fillRule;
if (this.overlayFill) {
ctx.fillStyle = this.overlayFill;
}
else if (this.fill) {
ctx.fillStyle = this.fill.toLiveGradient
? this.fill.toLiveGradient(ctx)
: this.fill;
}
if (this.stroke) {
ctx.strokeStyle = this.stroke;
}
ctx.beginPath();
this._render(ctx);
if (this.fill) {
ctx.fill();
}
if (this.stroke) {
ctx.strokeStyle = this.stroke;
ctx.lineWidth = this.strokeWidth;
ctx.lineCap = ctx.lineJoin = 'round';
ctx.stroke();
}
if (!noTransform && this.active) {
this.drawBorders(ctx);
this.hideCorners || this.drawCorners(ctx);
}
ctx.restore();
} | javascript | {
"resource": ""
} | |
q26420 | train | function(ctx) {
ctx.save();
var m = this.transformMatrix;
if (m) {
ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
}
this.transform(ctx);
for (var i = 0, l = this.paths.length; i < l; ++i) {
this.paths[i].render(ctx, true);
}
if (this.active) {
this.drawBorders(ctx);
this.hideCorners || this.drawCorners(ctx);
}
ctx.restore();
} | javascript | {
"resource": ""
} | |
q26421 | train | function(prop, value) {
if ((prop === 'fill' || prop === 'overlayFill') && value && this.isSameColor()) {
var i = this.paths.length;
while (i--) {
this.paths[i]._set(prop, value);
}
}
return this.callSuper('_set', prop, value);
} | javascript | {
"resource": ""
} | |
q26422 | train | function() {
return this.paths.reduce(function(total, path) {
return total + ((path && path.complexity) ? path.complexity() : 0);
}, 0);
} | javascript | {
"resource": ""
} | |
q26423 | train | function(object) {
this._restoreObjectsState();
removeFromArray(this.objects, object);
object.setActive(false);
this._calcBounds();
this._updateObjectsCoords();
return this;
} | javascript | {
"resource": ""
} | |
q26424 | train | function(ctx, noTransform) {
ctx.save();
this.transform(ctx);
var groupScaleFactor = Math.max(this.scaleX, this.scaleY);
for (var i = 0, len = this.objects.length, object; object = this.objects[i]; i++) {
var originalScaleFactor = object.borderScaleFactor;
object.borderScaleFactor = groupScaleFactor;
object.render(ctx);
object.borderScaleFactor = originalScaleFactor;
}
if (!noTransform && this.active) {
this.drawBorders(ctx);
this.hideCorners || this.drawCorners(ctx);
}
ctx.restore();
this.setCoords();
} | javascript | {
"resource": ""
} | |
q26425 | train | function() {
return this.getObjects().reduce(function(total, object) {
total += (typeof object.complexity == 'function') ? object.complexity() : 0;
return total;
}, 0);
} | javascript | {
"resource": ""
} | |
q26426 | train | function(object) {
var groupLeft = this.get('left'),
groupTop = this.get('top'),
groupAngle = this.getAngle() * (Math.PI / 180),
objectLeft = object.get('originalLeft'),
objectTop = object.get('originalTop'),
rotatedTop = Math.cos(groupAngle) * object.get('top') + Math.sin(groupAngle) * object.get('left'),
rotatedLeft = -Math.sin(groupAngle) * object.get('top') + Math.cos(groupAngle) * object.get('left');
object.setAngle(object.getAngle() + this.getAngle());
object.set('left', groupLeft + rotatedLeft * this.get('scaleX'));
object.set('top', groupTop + rotatedTop * this.get('scaleY'));
object.set('scaleX', object.get('scaleX') * this.get('scaleX'));
object.set('scaleY', object.get('scaleY') * this.get('scaleY'));
object.setCoords();
object.hideCorners = false;
object.setActive(false);
object.setCoords();
return this;
} | javascript | {
"resource": ""
} | |
q26427 | train | function(point) {
var halfWidth = this.get('width') / 2,
halfHeight = this.get('height') / 2,
centerX = this.get('left'),
centerY = this.get('top');
return centerX - halfWidth < point.x &&
centerX + halfWidth > point.x &&
centerY - halfHeight < point.y &&
centerY + halfHeight > point.y;
} | javascript | {
"resource": ""
} | |
q26428 | train | function(ctx, noTransform) {
ctx.save();
var m = this.transformMatrix;
this._resetWidthHeight();
if (this.group) {
ctx.translate(-this.group.width/2 + this.width/2, -this.group.height/2 + this.height/2);
}
if (m) {
ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
}
if (!noTransform) {
this.transform(ctx);
}
this._render(ctx);
if (this.active && !noTransform) {
this.drawBorders(ctx);
this.hideCorners || this.drawCorners(ctx);
}
ctx.restore();
} | javascript | {
"resource": ""
} | |
q26429 | train | function(element) {
this.setElement(fabric.util.getById(element));
fabric.util.addClass(this.getElement(), fabric.Image.CSS_CANVAS);
} | javascript | {
"resource": ""
} | |
q26430 | train | function() {
var canvasEl = fabric.document.createElement('canvas');
if (!canvasEl.getContext && typeof G_vmlCanvasManager != 'undefined') {
G_vmlCanvasManager.initElement(canvasEl);
}
this._render(canvasEl.getContext('2d'));
} | javascript | {
"resource": ""
} | |
q26431 | train | function(ctx, noTransform) {
ctx.save();
this._render(ctx);
if (!noTransform && this.active) {
this.drawBorders(ctx);
this.hideCorners || this.drawCorners(ctx);
}
ctx.restore();
} | javascript | {
"resource": ""
} | |
q26432 | train | function(name, value) {
if (name === 'fontFamily' && this.path) {
this.path = this.path.replace(/(.*?)([^\/]*)(\.font\.js)/, '$1' + value + '$3');
}
this.callSuper('_set', name, value);
} | javascript | {
"resource": ""
} | |
q26433 | limitNotifySubscribers | train | function limitNotifySubscribers(value, event) {
if (!event || event === defaultEvent) {
this._limitChange(value);
} else if (event === 'beforeChange') {
this._limitBeforeChange(value);
} else {
this._origNotifySubscribers(value, event);
}
} | javascript | {
"resource": ""
} |
q26434 | makeAccessorsFromFunction | train | function makeAccessorsFromFunction(callback) {
return ko.utils.objectMap(ko.dependencyDetection.ignore(callback), function(value, key) {
return function() {
return callback()[key];
};
});
} | javascript | {
"resource": ""
} |
q26435 | update | train | function update() {
min = isAttrNum(slider.min) ? +slider.min : 0;
max = isAttrNum(slider.max) ? +slider.max : 100;
if (max < min)
max = min > 100 ? min : 100;
step = isAttrNum(slider.step) && slider.step > 0 ? +slider.step : 1;
range = max - min;
draw(true);
} | javascript | {
"resource": ""
} |
q26436 | calc | train | function calc() {
if (!isValueSet && !areAttrsSet)
value = slider.getAttribute('value');
if (!isAttrNum(value))
value = (min + max) / 2;;
// snap to step intervals (WebKit sometimes does not - bug?)
value = Math.round((value - min) / step) * step + min;
if (value < min)
value = min;
else if (value > max)
value = min + ~~(range / step) * step;
} | javascript | {
"resource": ""
} |
q26437 | draw | train | function draw(attrsModified) {
calc();
if (isChanged && value != prevValue)
slider.dispatchEvent(onChange);
isChanged = false;
if (!attrsModified && value == prevValue)
return;
prevValue = value;
var position = range ? (value - min) / range * 100 : 0;
var bg = '-moz-element(#__sliderthumb__) ' + position + '% no-repeat, ';
style(slider, { background: bg + track });
} | javascript | {
"resource": ""
} |
q26438 | before_photo_post | train | function before_photo_post(test, callback){
hello(test.network)
.api("me/albums")
.then(function(r){
for(var i=0;i<r.data.length;i++){
if(r.data[i].name === "TestAlbum"){
var id = r.data[i].id;
test.data.id = id;
return callback();
}
}
callback("Failed to setup: Could not find the album 'TestAlbum'");
}, function(){
callback("Failed to setup: could not access me/albums");
});
} | javascript | {
"resource": ""
} |
q26439 | DictionaryItem | train | function DictionaryItem(key, value) {
this.key = ko.observable(key);
this.options = [];
if(value instanceof Array){
this.options = value;
value = value[0];
}
this.value = (typeof(value)==='function')? value : ko.observable(value);
} | javascript | {
"resource": ""
} |
q26440 | Dictionary | train | function Dictionary(data) {
this.items = ko.observableArray([]);
for (var field in data) {
if (data.hasOwnProperty(field)) {
this.items.push(new DictionaryItem(field, data[field]));
}
}
this.addItem = function() {
this.items.push(new DictionaryItem());
}.bind(this);
this.removeItem = function(item) {
this.items.remove(item);
}.bind(this);
this.itemsAsObject = ko.dependentObservable(function() {
var result = {};
ko.utils.arrayForEach(this.items(), function(item) {
result[item.key()] = item.value;
});
return result;
}, this);
} | javascript | {
"resource": ""
} |
q26441 | _indexOf | train | function _indexOf(a,s){
// Do we need the hack?
if(a.indexOf){
return a.indexOf(s);
}
for(var j=0;j<a.length;j++){
if(a[j]===s){
return j;
}
}
return -1;
} | javascript | {
"resource": ""
} |
q26442 | every | train | function every (arr, fn, thisObj) {
var scope = thisObj || global;
for (var i = 0, j = arr.length; i < j; ++i) {
if (!fn.call(scope, arr[i], i, arr)) {
return false;
}
}
return true;
} | javascript | {
"resource": ""
} |
q26443 | img_xhr | train | function img_xhr(img, url) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
img.src = window.URL.createObjectURL(this.response);
};
xhr.send();
} | javascript | {
"resource": ""
} |
q26444 | fileRef | train | function fileRef(item, network, bucket, selected){
this.els = [];
this.selected = false;
this.item = {};
// Item contents change
this.update = function(item){
if(!item){
return this.item;
}
else {
// Merge the two together
this.item = hello.utils.merge(this.item, item);
}
// Loop through the elements and update their content
for(var i=0;i<this.els.length;i++){
this.els[i].getElementsByTagName('span')[0].innerHTML = this.item.name;
if(this.item.thumbnail){
this.els[i].getElementsByTagName('img')[0].src = this.item.thumbnail;
}
}
};
// Create an element in the given bucket,
// adding on click event handlers
this.create = function(bucket){
var item = this.item;
var self = this;
var el = doc.createElement('li');
el.title = item.name;
el.innerHTML = "<img "+(item.thumbnail?"src='"+item.thumbnail+"'":"")+"/>"
+"<span>"+(item.name||'')+"</span>";
el.onclick = function(){
// Is this a folder?
if(item.type==='folder'||item.type==='album'){
getBucket(network+":"+(item.files?item.files:item.id+"/files"), item.name, bucket.id );
}
else {
// Toggle selected
self.toggleSelect();
}
};
// Add to bucket
bucket.appendChild(el);
// Add to local store
this.els.push(el);
return el;
};
this.toggleSelect = function(bool){
if(bool===this.selected){
// nothing
return;
}
// else change
// toggle
this.selected = !this.selected;
// Selected
if(this.selected){
// Does the element exist within the local bucket
var local = false;
for(i=0;i<this.els.length;i++){
if( this.els[i].parentNode === select_el ){
local=true;
break;
}
}
if(!local){
// create it
this.create(select_el);
}
}
// Loop through the elements and update their content
for(i=0;i<this.els.length;i++){
this.els[i].className = this.selected ? "select" : "";
}
// get the number of selected items in ref and update
info_el.innerHTML = ( this.selected ? ++global_counter : --global_counter );
};
// Create the initial element
this.update(item);
this.create(bucket);
// if this is selected
if(selected){
this.toggleSelect();
}
} | javascript | {
"resource": ""
} |
q26445 | uploadFileList | train | function uploadFileList(files){
// FileList
if(!("FileList" in window) || (files instanceof File) || (files instanceof Blob)){
// Make an Array
files = [files];
}
var max = 20, len = files.length;
if(len>max){
var bool = confirm("You man only upload "+max+" files at a time");
if(!bool){
return;
}
len = max;
}
// Loop through the array and place the items on the page
for(var i=0;i<len;i++){
createRef(files[i]);
}
} | javascript | {
"resource": ""
} |
q26446 | createRef | train | function createRef(file){
// Create a new fileRef
var pointer = new fileRef({
name : file.name,
type : file.type,
file : file
}, current_network, current_bucket, true);
ref.push( pointer );
if(current_folder==="local"){
readFile(file, function(dataURL){
// Update list
pointer.update({
thumbnail : dataURL,
picture : dataURL
});
});
}
else{
// Upload the files to the current directory
hello.api(current_folder, "post", {file: file}, function(r){
// Once the files have been successfully upload lets update the pointer
pointer.update({
id : r.id,
thumbnail : r.source,
picture : r.source
});
});
}
} | javascript | {
"resource": ""
} |
q26447 | readFile | train | function readFile(file, callback){
// Run this sequentially
sync(function(){
// Create a new FileReader Object
var reader = new FileReader();
// Set an onload handler because we load files into it Asynchronously
reader.onload = function(e){
// Print onto Canvas
callback( this.result );
// Run the next one;
sync();
};
reader.readAsDataURL(file);
});
} | javascript | {
"resource": ""
} |
q26448 | query | train | function query(p, callback) {
if (p.data) {
extend(p.query, p.data);
p.data = null;
}
callback(p.path);
} | javascript | {
"resource": ""
} |
q26449 | without | train | function without(remove) {
// Calling .without() with no arguments is a no-op. Don't bother cloning.
if (typeof remove === "undefined" && arguments.length === 0) {
return this;
}
if (typeof remove !== "function") {
// If we weren't given an array, use the arguments list.
var keysToRemoveArray = (Array.isArray(remove)) ?
remove.slice() : Array.prototype.slice.call(arguments);
// Convert numeric keys to strings since that's how they'll
// come from the enumeration of the object.
keysToRemoveArray.forEach(function(el, idx, arr) {
if(typeof(el) === "number") {
arr[idx] = el.toString();
}
});
remove = function(val, key) {
return keysToRemoveArray.indexOf(key) !== -1;
};
}
var result = instantiateEmptyObject(this);
for (var key in this) {
if (this.hasOwnProperty(key) && remove(this[key], key) === false) {
result[key] = this[key];
}
}
return makeImmutableObject(result);
} | javascript | {
"resource": ""
} |
q26450 | merge | train | function merge(other, config) {
// Calling .merge() with no arguments is a no-op. Don't bother cloning.
if (arguments.length === 0) {
return this;
}
if (other === null || (typeof other !== "object")) {
throw new TypeError("Immutable#merge can only be invoked with objects or arrays, not " + JSON.stringify(other));
}
var receivedArray = (Array.isArray(other)),
deep = config && config.deep,
mode = config && config.mode || 'merge',
merger = config && config.merger,
result;
// Use the given key to extract a value from the given object, then place
// that value in the result object under the same key. If that resulted
// in a change from this object's value at that key, set anyChanges = true.
function addToResult(currentObj, otherObj, key) {
var immutableValue = Immutable(otherObj[key]);
var mergerResult = merger && merger(currentObj[key], immutableValue, config);
var currentValue = currentObj[key];
if ((result !== undefined) ||
(mergerResult !== undefined) ||
(!currentObj.hasOwnProperty(key)) ||
!isEqual(immutableValue, currentValue)) {
var newValue;
if (mergerResult !== undefined) {
newValue = mergerResult;
} else if (deep && isMergableObject(currentValue) && isMergableObject(immutableValue)) {
newValue = Immutable.merge(currentValue, immutableValue, config);
} else {
newValue = immutableValue;
}
if (!isEqual(currentValue, newValue) || !currentObj.hasOwnProperty(key)) {
if (result === undefined) {
// Make a shallow clone of the current object.
result = quickCopy(currentObj, instantiateEmptyObject(currentObj));
}
result[key] = newValue;
}
}
}
function clearDroppedKeys(currentObj, otherObj) {
for (var key in currentObj) {
if (!otherObj.hasOwnProperty(key)) {
if (result === undefined) {
// Make a shallow clone of the current object.
result = quickCopy(currentObj, instantiateEmptyObject(currentObj));
}
delete result[key];
}
}
}
var key;
// Achieve prioritization by overriding previous values that get in the way.
if (!receivedArray) {
// The most common use case: just merge one object into the existing one.
for (key in other) {
if (Object.getOwnPropertyDescriptor(other, key)) {
addToResult(this, other, key);
}
}
if (mode === 'replace') {
clearDroppedKeys(this, other);
}
} else {
// We also accept an Array
for (var index = 0, length = other.length; index < length; index++) {
var otherFromArray = other[index];
for (key in otherFromArray) {
if (otherFromArray.hasOwnProperty(key)) {
addToResult(result !== undefined ? result : this, otherFromArray, key);
}
}
}
}
if (result === undefined) {
return this;
} else {
return makeImmutableObject(result);
}
} | javascript | {
"resource": ""
} |
q26451 | addToResult | train | function addToResult(currentObj, otherObj, key) {
var immutableValue = Immutable(otherObj[key]);
var mergerResult = merger && merger(currentObj[key], immutableValue, config);
var currentValue = currentObj[key];
if ((result !== undefined) ||
(mergerResult !== undefined) ||
(!currentObj.hasOwnProperty(key)) ||
!isEqual(immutableValue, currentValue)) {
var newValue;
if (mergerResult !== undefined) {
newValue = mergerResult;
} else if (deep && isMergableObject(currentValue) && isMergableObject(immutableValue)) {
newValue = Immutable.merge(currentValue, immutableValue, config);
} else {
newValue = immutableValue;
}
if (!isEqual(currentValue, newValue) || !currentObj.hasOwnProperty(key)) {
if (result === undefined) {
// Make a shallow clone of the current object.
result = quickCopy(currentObj, instantiateEmptyObject(currentObj));
}
result[key] = newValue;
}
}
} | javascript | {
"resource": ""
} |
q26452 | makeImmutableObject | train | function makeImmutableObject(obj) {
if (!globalConfig.use_static) {
addPropertyTo(obj, "merge", merge);
addPropertyTo(obj, "replace", objectReplace);
addPropertyTo(obj, "without", without);
addPropertyTo(obj, "asMutable", asMutableObject);
addPropertyTo(obj, "set", objectSet);
addPropertyTo(obj, "setIn", objectSetIn);
addPropertyTo(obj, "update", update);
addPropertyTo(obj, "updateIn", updateIn);
addPropertyTo(obj, "getIn", getIn);
}
return makeImmutable(obj, mutatingObjectMethods);
} | javascript | {
"resource": ""
} |
q26453 | toStatic | train | function toStatic(fn) {
function staticWrapper() {
var args = [].slice.call(arguments);
var self = args.shift();
return fn.apply(self, args);
}
return staticWrapper;
} | javascript | {
"resource": ""
} |
q26454 | toStaticObjectOrArray | train | function toStaticObjectOrArray(fnObject, fnArray) {
function staticWrapper() {
var args = [].slice.call(arguments);
var self = args.shift();
if (Array.isArray(self)) {
return fnArray.apply(self, args);
} else {
return fnObject.apply(self, args);
}
}
return staticWrapper;
} | javascript | {
"resource": ""
} |
q26455 | train | function(){
var origSrc = originalSource($scope);
$scope.$uisSource = Object.keys(origSrc).map(function(v){
var result = {};
result[ctrl.parserResult.keyName] = v;
result.value = origSrc[v];
return result;
});
} | javascript | {
"resource": ""
} | |
q26456 | _handleMatchSelection | train | function _handleMatchSelection(key){
var caretPosition = _getCaretPosition($select.searchInput[0]),
length = $select.selected.length,
// none = -1,
first = 0,
last = length-1,
curr = $selectMultiple.activeMatchIndex,
next = $selectMultiple.activeMatchIndex+1,
prev = $selectMultiple.activeMatchIndex-1,
newIndex = curr;
if(caretPosition > 0 || ($select.search.length && key == KEY.RIGHT)) return false;
$select.close();
function getNewActiveMatchIndex(){
switch(key){
case KEY.LEFT:
// Select previous/first item
if(~$selectMultiple.activeMatchIndex) return prev;
// Select last item
else return last;
break;
case KEY.RIGHT:
// Open drop-down
if(!~$selectMultiple.activeMatchIndex || curr === last){
$select.activate();
return false;
}
// Select next/last item
else return next;
break;
case KEY.BACKSPACE:
// Remove selected item and select previous/first
if(~$selectMultiple.activeMatchIndex){
if($selectMultiple.removeChoice(curr)) {
return prev;
} else {
return curr;
}
} else {
// If nothing yet selected, select last item
return last;
}
break;
case KEY.DELETE:
// Remove selected item and select next item
if(~$selectMultiple.activeMatchIndex){
$selectMultiple.removeChoice($selectMultiple.activeMatchIndex);
return curr;
}
else return false;
}
}
newIndex = getNewActiveMatchIndex();
if(!$select.selected.length || newIndex === false) $selectMultiple.activeMatchIndex = -1;
else $selectMultiple.activeMatchIndex = Math.min(last,Math.max(first,newIndex));
return true;
} | javascript | {
"resource": ""
} |
q26457 | parseXML | train | function parseXML(xml) {
if ( window.DOMParser == undefined && window.ActiveXObject ) {
DOMParser = function() { };
DOMParser.prototype.parseFromString = function( xmlString ) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML( xmlString );
return doc;
};
}
try {
var xmlDoc = ( new DOMParser() ).parseFromString( xml, 'text/xml' );
if ( $.isXMLDoc( xmlDoc ) ) {
var err = $('parsererror', xmlDoc);
if ( err.length == 1 ) {
throw new Error('Error: ' + $(xmlDoc).text() );
}
} else {
throw new Error('Unable to parse XML');
}
return xmlDoc;
} catch( e ) {
var msg = ( e.name == undefined ? e : e.name + ': ' + e.message );
$(document).trigger('xmlParseError', [ msg ]);
return undefined;
}
} | javascript | {
"resource": ""
} |
q26458 | isMockDataEqual | train | function isMockDataEqual( mock, live ) {
var identical = true;
// Test for situations where the data is a querystring (not an object)
if (typeof live === 'string') {
// Querystring may be a regex
return $.isFunction( mock.test ) ? mock.test(live) : mock == live;
}
$.each(mock, function(k) {
if ( live[k] === undefined ) {
identical = false;
return identical;
} else {
if ( typeof live[k] === 'object' && live[k] !== null ) {
if ( identical && $.isArray( live[k] ) ) {
identical = $.isArray( mock[k] ) && live[k].length === mock[k].length;
}
identical = identical && isMockDataEqual(mock[k], live[k]);
} else {
if ( mock[k] && $.isFunction( mock[k].test ) ) {
identical = identical && mock[k].test(live[k]);
} else {
identical = identical && ( mock[k] == live[k] );
}
}
}
});
return identical;
} | javascript | {
"resource": ""
} |
q26459 | getMockForRequest | train | function getMockForRequest( handler, requestSettings ) {
// If the mock was registered with a function, let the function decide if we
// want to mock this request
if ( $.isFunction(handler) ) {
return handler( requestSettings );
}
// Inspect the URL of the request and check if the mock handler's url
// matches the url for this ajax request
if ( $.isFunction(handler.url.test) ) {
// The user provided a regex for the url, test it
if ( !handler.url.test( requestSettings.url ) ) {
return null;
}
} else {
// Look for a simple wildcard '*' or a direct URL match
var star = handler.url.indexOf('*');
if (handler.url !== requestSettings.url && star === -1 ||
!new RegExp(handler.url.replace(/[-[\]{}()+?.,\\^$|#\s]/g, "\\$&").replace(/\*/g, '.+')).test(requestSettings.url)) {
return null;
}
}
// Inspect the data submitted in the request (either POST body or GET query string)
if ( handler.data ) {
if ( ! requestSettings.data || !isMockDataEqual(handler.data, requestSettings.data) ) {
// They're not identical, do not mock this request
return null;
}
}
// Inspect the request type
if ( handler && handler.type &&
handler.type.toLowerCase() != requestSettings.type.toLowerCase() ) {
// The request type doesn't match (GET vs. POST)
return null;
}
return handler;
} | javascript | {
"resource": ""
} |
q26460 | xhr | train | function xhr(mockHandler, requestSettings, origSettings, origHandler) {
// Extend with our default mockjax settings
mockHandler = $.extend(true, {}, $.mockjaxSettings, mockHandler);
if (typeof mockHandler.headers === 'undefined') {
mockHandler.headers = {};
}
if (typeof requestSettings.headers === 'undefined') {
requestSettings.headers = {};
}
if ( mockHandler.contentType ) {
mockHandler.headers['content-type'] = mockHandler.contentType;
}
return {
status: mockHandler.status,
statusText: mockHandler.statusText,
readyState: 1,
open: function() { },
send: function() {
origHandler.fired = true;
_xhrSend.call(this, mockHandler, requestSettings, origSettings);
},
abort: function() {
clearTimeout(this.responseTimer);
},
setRequestHeader: function(header, value) {
requestSettings.headers[header] = value;
},
getResponseHeader: function(header) {
// 'Last-modified', 'Etag', 'content-type' are all checked by jQuery
if ( mockHandler.headers && mockHandler.headers[header] ) {
// Return arbitrary headers
return mockHandler.headers[header];
} else if ( header.toLowerCase() == 'last-modified' ) {
return mockHandler.lastModified || (new Date()).toString();
} else if ( header.toLowerCase() == 'etag' ) {
return mockHandler.etag || '';
} else if ( header.toLowerCase() == 'content-type' ) {
return mockHandler.contentType || 'text/plain';
}
},
getAllResponseHeaders: function() {
var headers = '';
// since jQuery 1.9 responseText type has to match contentType
if (mockHandler.contentType) {
mockHandler.headers['Content-Type'] = mockHandler.contentType;
}
$.each(mockHandler.headers, function(k, v) {
headers += k + ': ' + v + "\n";
});
return headers;
}
};
} | javascript | {
"resource": ""
} |
q26461 | processJsonpMock | train | function processJsonpMock( requestSettings, mockHandler, origSettings ) {
// Handle JSONP Parameter Callbacks, we need to replicate some of the jQuery core here
// because there isn't an easy hook for the cross domain script tag of jsonp
processJsonpUrl( requestSettings );
requestSettings.dataType = "json";
if(requestSettings.data && CALLBACK_REGEX.test(requestSettings.data) || CALLBACK_REGEX.test(requestSettings.url)) {
createJsonpCallback(requestSettings, mockHandler, origSettings);
// We need to make sure
// that a JSONP style response is executed properly
var rurl = /^(\w+:)?\/\/([^\/?#]+)/,
parts = rurl.exec( requestSettings.url ),
remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);
requestSettings.dataType = "script";
if(requestSettings.type.toUpperCase() === "GET" && remote ) {
var newMockReturn = processJsonpRequest( requestSettings, mockHandler, origSettings );
// Check if we are supposed to return a Deferred back to the mock call, or just
// signal success
if(newMockReturn) {
return newMockReturn;
} else {
return true;
}
}
}
return null;
} | javascript | {
"resource": ""
} |
q26462 | processJsonpUrl | train | function processJsonpUrl( requestSettings ) {
if ( requestSettings.type.toUpperCase() === "GET" ) {
if ( !CALLBACK_REGEX.test( requestSettings.url ) ) {
requestSettings.url += (/\?/.test( requestSettings.url ) ? "&" : "?") +
(requestSettings.jsonp || "callback") + "=?";
}
} else if ( !requestSettings.data || !CALLBACK_REGEX.test(requestSettings.data) ) {
requestSettings.data = (requestSettings.data ? requestSettings.data + "&" : "") + (requestSettings.jsonp || "callback") + "=?";
}
} | javascript | {
"resource": ""
} |
q26463 | processJsonpRequest | train | function processJsonpRequest( requestSettings, mockHandler, origSettings ) {
// Synthesize the mock request for adding a script tag
var callbackContext = origSettings && origSettings.context || requestSettings,
newMock = null;
// If the response handler on the moock is a function, call it
if ( mockHandler.response && $.isFunction(mockHandler.response) ) {
mockHandler.response(origSettings);
} else {
// Evaluate the responseText javascript in a global context
if( typeof mockHandler.responseText === 'object' ) {
$.globalEval( '(' + JSON.stringify( mockHandler.responseText ) + ')');
} else {
$.globalEval( '(' + mockHandler.responseText + ')');
}
}
// Successful response
setTimeout(function() {
jsonpSuccess( requestSettings, callbackContext, mockHandler );
jsonpComplete( requestSettings, callbackContext, mockHandler );
}, parseResponseTimeOpt(mockHandler.responseTime) || 0);
// If we are running under jQuery 1.5+, return a deferred object
if($.Deferred){
newMock = new $.Deferred();
if(typeof mockHandler.responseText == "object"){
newMock.resolveWith( callbackContext, [mockHandler.responseText] );
}
else{
newMock.resolveWith( callbackContext, [$.parseJSON( mockHandler.responseText )] );
}
}
return newMock;
} | javascript | {
"resource": ""
} |
q26464 | createJsonpCallback | train | function createJsonpCallback( requestSettings, mockHandler, origSettings ) {
var callbackContext = origSettings && origSettings.context || requestSettings;
var jsonp = requestSettings.jsonpCallback || ("jsonp" + jsc++);
// Replace the =? sequence both in the query string and the data
if ( requestSettings.data ) {
requestSettings.data = (requestSettings.data + "").replace(CALLBACK_REGEX, "=" + jsonp + "$1");
}
requestSettings.url = requestSettings.url.replace(CALLBACK_REGEX, "=" + jsonp + "$1");
// Handle JSONP-style loading
window[ jsonp ] = window[ jsonp ] || function( tmp ) {
data = tmp;
jsonpSuccess( requestSettings, callbackContext, mockHandler );
jsonpComplete( requestSettings, callbackContext, mockHandler );
// Garbage collect
window[ jsonp ] = undefined;
try {
delete window[ jsonp ];
} catch(e) {}
if ( head ) {
head.removeChild( script );
}
};
} | javascript | {
"resource": ""
} |
q26465 | jsonpSuccess | train | function jsonpSuccess(requestSettings, callbackContext, mockHandler) {
// If a local callback was specified, fire it and pass it the data
if ( requestSettings.success ) {
requestSettings.success.call( callbackContext, mockHandler.responseText || "", status, {} );
}
// Fire the global callback
if ( requestSettings.global ) {
(requestSettings.context ? $(requestSettings.context) : $.event).trigger("ajaxSuccess", [{}, requestSettings]);
}
} | javascript | {
"resource": ""
} |
q26466 | jsonpComplete | train | function jsonpComplete(requestSettings, callbackContext) {
// Process result
if ( requestSettings.complete ) {
requestSettings.complete.call( callbackContext, {} , status );
}
// The request was completed
if ( requestSettings.global ) {
(requestSettings.context ? $(requestSettings.context) : $.event).trigger("ajaxComplete", [{}, requestSettings]);
}
// Handle the global AJAX counter
if ( requestSettings.global && ! --$.active ) {
$.event.trigger( "ajaxStop" );
}
} | javascript | {
"resource": ""
} |
q26467 | copyUrlParameters | train | function copyUrlParameters(mockHandler, origSettings) {
//parameters aren't captured if the URL isn't a RegExp
if (!(mockHandler.url instanceof RegExp)) {
return;
}
//if no URL params were defined on the handler, don't attempt a capture
if (!mockHandler.hasOwnProperty('urlParams')) {
return;
}
var captures = mockHandler.url.exec(origSettings.url);
//the whole RegExp match is always the first value in the capture results
if (captures.length === 1) {
return;
}
captures.shift();
//use handler params as keys and capture resuts as values
var i = 0,
capturesLength = captures.length,
paramsLength = mockHandler.urlParams.length,
//in case the number of params specified is less than actual captures
maxIterations = Math.min(capturesLength, paramsLength),
paramValues = {};
for (i; i < maxIterations; i++) {
var key = mockHandler.urlParams[i];
paramValues[key] = captures[i];
}
origSettings.urlParams = paramValues;
} | javascript | {
"resource": ""
} |
q26468 | getMimeType | train | function getMimeType(types) {
if (!types) return MSIE_MIME_TYPE; // IE 9 workaround.
for (var i = 0; i < types.length; i++) {
if (types[i] == MSIE_MIME_TYPE || types[i] == EDGE_MIME_TYPE ||
types[i].substr(0, MIME_TYPE.length) == MIME_TYPE) {
return types[i];
}
}
return null;
} | javascript | {
"resource": ""
} |
q26469 | getItemType | train | function getItemType(mimeType) {
if (dndState.isDragging) return dndState.itemType || undefined;
if (mimeType == MSIE_MIME_TYPE || mimeType == EDGE_MIME_TYPE) return null;
return (mimeType && mimeType.substr(MIME_TYPE.length + 1)) || undefined;
} | javascript | {
"resource": ""
} |
q26470 | getPlaceholderElement | train | function getPlaceholderElement() {
var placeholder;
angular.forEach(element.children(), function(childNode) {
var child = angular.element(childNode);
if (child.hasClass('dndPlaceholder')) {
placeholder = child;
}
});
return placeholder || angular.element("<li class='dndPlaceholder'></li>");
} | javascript | {
"resource": ""
} |
q26471 | filterEffects | train | function filterEffects(effects, effectAllowed) {
if (effectAllowed == 'all') return effects;
return effects.filter(function(effect) {
return effectAllowed.toLowerCase().indexOf(effect) != -1;
});
} | javascript | {
"resource": ""
} |
q26472 | install | train | function install(runtime, abi, platform, arch, cb) {
const essential = runtime + '-v' + abi + '-' + platform + '-' + arch;
const pkgVersion = pkg.version;
const currentPlatform = pkg.name + '-v' + pkgVersion + '-' + essential;
console.log('Downloading prebuild for platform:', currentPlatform);
let downloadUrl = 'https://github.com/WilixLead/iohook/releases/download/v' + pkgVersion + '/' + currentPlatform + '.tar.gz';
let reqOpts = {url: downloadUrl};
let tempFile = path.join(os.tmpdir(), 'prebuild.tar.gz');
let req = get(reqOpts, function(err, res) {
if (err) {
return onerror(err);
}
if (res.statusCode !== 200) {
if (res.statusCode === 404) {
console.error('Prebuild for current platform (' + currentPlatform + ') not found!');
console.error('Try to compile for your platform:');
console.error('# cd node_modules/iohook;');
console.error('# npm run compile');
console.error('');
return onerror('Prebuild for current platform (' + currentPlatform + ') not found!');
}
return onerror('Bad response from prebuild server. Code: ' + res.statusCode);
}
pump(res, fs.createWriteStream(tempFile), function(err) {
if (err) {
throw err;
}
let options = {
readable: true,
writable: true,
hardlinkAsFilesFallback: true
};
let binaryName;
let updateName = function(entry) {
if (/\.node$/i.test(entry.name)) binaryName = entry.name
};
let targetFile = path.join(__dirname, 'builds', essential);
let extract = tfs.extract(targetFile, options)
.on('entry', updateName);
pump(fs.createReadStream(tempFile), zlib.createGunzip(), extract, function(err) {
if (err) {
return onerror(err);
}
cb()
})
})
});
req.setTimeout(30 * 1000, function() {
req.abort()
})
} | javascript | {
"resource": ""
} |
q26473 | optionsFromPackage | train | function optionsFromPackage(attempts) {
attempts = attempts || 2;
if (attempts > 5) {
console.log('Can\'t resolve main package.json file');
return {
targets: [],
platforms: [process.platform],
arches: [process.arch]
}
}
let mainPath = Array(attempts).join("../");
try {
const content = fs.readFileSync(path.join(__dirname, mainPath, 'package.json'), 'utf-8');
const packageJson = JSON.parse(content);
const opts = packageJson.iohook || {};
if (!opts.targets) {
opts.targets = []
}
if (!opts.platforms) opts.platforms = [process.platform];
if (!opts.arches) opts.arches = [process.arch];
return opts
} catch (e) {
return optionsFromPackage(attempts + 1);
}
} | javascript | {
"resource": ""
} |
q26474 | listenHandler | train | function listenHandler( event ) {
var handler = rawHandler.apply( this, arguments );
if ( handler === false) {
event.stopPropagation();
event.preventDefault();
}
return( handler );
} | javascript | {
"resource": ""
} |
q26475 | attachHandler | train | function attachHandler() {
var handler = rawHandler.call( element, window.event );
if ( handler === false ) {
window.event.returnValue = false;
window.event.cancelBubble = true;
}
return( handler );
} | javascript | {
"resource": ""
} |
q26476 | removeEvent | train | function removeEvent( token ) {
if ( token.element.removeEventListener ) {
token.element.removeEventListener( token.event, token.handler );
} else {
token.element.detachEvent( 'on' + token.event, token.handler );
}
} | javascript | {
"resource": ""
} |
q26477 | getStyle | train | function getStyle( element, property ) {
return (
typeof getComputedStyle !== 'undefined'
? getComputedStyle( element, null)
: element.currentStyle
)[ property ]; // avoid getPropertyValue altogether
} | javascript | {
"resource": ""
} |
q26478 | toggleClasses | train | function toggleClasses( element, state, openingClass, closingClass ) {
if( state === 'opening' || state === 'open' ) {
var oldClass = openingClass || 'au-accordion--closed';
var newClass = closingClass || 'au-accordion--open';
}
else {
var oldClass = closingClass || 'au-accordion--open';
var newClass = openingClass || 'au-accordion--closed';
}
removeClass( element, oldClass );
addClass( element, newClass );
} | javascript | {
"resource": ""
} |
q26479 | ExitHandler | train | function ExitHandler( exiting, error ) {
if( error ) {
if( error.stack ) {
console.error( error.stack );
}
process.exit( 1 );
}
if( exiting.now ) {
process.exit( 0 ); // exit now
}
console.log('\n');
process.exit( 0 ); // now exit with a smile :)
} | javascript | {
"resource": ""
} |
q26480 | checkCliDependency | train | function checkCliDependency(ctx) {
var result = spawnSync('cordova-hcp', [], { cwd: './plugins/' + ctx.opts.plugin.id });
if (!result.error) {
return;
}
suggestCliInstallation();
} | javascript | {
"resource": ""
} |
q26481 | suggestCliInstallation | train | function suggestCliInstallation() {
console.log('---------CHCP-------------');
console.log('To make the development process easier for you - we developed a CLI client for our plugin.');
console.log('To install it, please, use command:');
console.log('npm install -g cordova-hot-code-push-cli');
console.log('For more information please visit https://github.com/nordnet/cordova-hot-code-push-cli');
console.log('--------------------------');
} | javascript | {
"resource": ""
} |
q26482 | isInstallationAlreadyPerformed | train | function isInstallationAlreadyPerformed(ctx) {
var pathToInstallFlag = path.join(ctx.opts.projectRoot, 'plugins', ctx.opts.plugin.id, INSTALLATION_FLAG_FILE_NAME);
try {
fs.accessSync(pathToInstallFlag, fs.F_OK);
return true;
} catch (err) {
return false;
}
} | javascript | {
"resource": ""
} |
q26483 | createPluginInstalledFlag | train | function createPluginInstalledFlag(ctx) {
var pathToInstallFlag = path.join(ctx.opts.projectRoot, 'plugins', ctx.opts.plugin.id, INSTALLATION_FLAG_FILE_NAME);
fs.closeSync(fs.openSync(pathToInstallFlag, 'w'));
} | javascript | {
"resource": ""
} |
q26484 | readOptions | train | function readOptions(ctx) {
var configFilePath = path.join(ctx.opts.projectRoot, 'config.xml');
var configXmlContent = xmlHelper.readXmlAsJson(configFilePath, true);
return parseConfig(configXmlContent);
} | javascript | {
"resource": ""
} |
q26485 | broadcastEventFromNative | train | function broadcastEventFromNative(nativeMessage) {
var params = {};
if (nativeMessage.error != null) {
params.error = nativeMessage.error;
}
var chcpEvent = new CustomEvent(nativeMessage.action, {
'detail': params
});
document.dispatchEvent(chcpEvent);
} | javascript | {
"resource": ""
} |
q26486 | train | function(options, callback) {
if (options === undefined || options == null) {
return;
}
callNativeMethod(pluginNativeMethod.CONFIGURE, options, callback);
} | javascript | {
"resource": ""
} | |
q26487 | setup | train | function setup(context) {
cordovaContext = context;
platforms = context.opts.platforms;
projectRoot = context.opts.projectRoot;
} | javascript | {
"resource": ""
} |
q26488 | getProjectName | train | function getProjectName(ctx, projectRoot) {
var cordova_util = ctx.requireCordovaModule('cordova-lib/src/cordova/util');
var xml = cordova_util.projectConfig(projectRoot);
var ConfigParser;
// If we are running Cordova 5.4 or abova - use parser from cordova-common.
// Otherwise - from cordova-lib.
try {
ConfigParser = ctx.requireCordovaModule('cordova-common/src/ConfigParser/ConfigParser');
} catch (e) {
ConfigParser = ctx.requireCordovaModule('cordova-lib/src/configparser/ConfigParser')
}
return new ConfigParser(xml).name();
} | javascript | {
"resource": ""
} |
q26489 | getPlatformSpecificConfigXml | train | function getPlatformSpecificConfigXml(platform) {
var configFilePath = null;
switch (platform) {
case 'ios':
{
configFilePath = pathToIosConfigXml();
break;
}
case 'android':
{
configFilePath = pathToAndroidConfigXml();
break;
}
}
return configFilePath;
} | javascript | {
"resource": ""
} |
q26490 | injectOptions | train | function injectOptions(options) {
platforms.forEach(function(platform) {
var configXmlFilePath = getPlatformSpecificConfigXml(platform);
if (configXmlFilePath == null) {
return;
}
// read data from config.xml
var configData = xmlHelper.readXmlAsJson(configXmlFilePath);
if (configData == null) {
console.warn('Configuration file ' + configXmlFilePath + ' not found');
return;
}
// inject new options
var chcpXmlConfig = {};
for (var preferenceName in options) {
injectPreference(chcpXmlConfig, preferenceName, options[preferenceName]);
}
// write them back to config.xml
configData.widget['chcp'] = [];
configData.widget.chcp.push(chcpXmlConfig);
xmlHelper.writeJsonAsXml(configData, configXmlFilePath);
});
} | javascript | {
"resource": ""
} |
q26491 | processConsoleOptions | train | function processConsoleOptions(ctx) {
var consoleOptions = ctx.opts.options;
// If we are using Cordova 5.3.3 or lower - arguments are array of strings.
// Will be removed after some time.
if (consoleOptions instanceof Array) {
return processConsoleOptions_cordova_53(consoleOptions);
}
// for newer version of Cordova - they are an object of properties
return processConsoleOptions_cordova_54(consoleOptions);
} | javascript | {
"resource": ""
} |
q26492 | prepareWithCustomBuildOption | train | function prepareWithCustomBuildOption(ctx, optionName, chcpXmlOptions) {
if (optionName.length == 0) {
return false;
}
var buildConfig = chcpBuildOptions.getBuildConfigurationByName(ctx, optionName);
if (buildConfig == null) {
console.warn('Build configuration for "' + optionName + '" not found in chcp.options. Ignoring it.');
return false;
}
console.log('Using config from chcp.options:');
console.log(JSON.stringify(buildConfig, null, 2));
mergeBuildOptions(chcpXmlOptions, buildConfig);
console.log('Resulting config will contain the following preferences:');
console.log(JSON.stringify(chcpXmlOptions, null, 2));
chcpConfigXmlWriter.writeOptions(ctx, chcpXmlOptions);
return true;
} | javascript | {
"resource": ""
} |
q26493 | setWKWebViewEngineMacro | train | function setWKWebViewEngineMacro(cordovaContext) {
init(cordovaContext);
// injecting options in project file
var projectFile = loadProjectFile();
setMacro(projectFile.xcode);
projectFile.write();
} | javascript | {
"resource": ""
} |
q26494 | init | train | function init(ctx) {
context = ctx;
projectRoot = ctx.opts.projectRoot;
projectName = getProjectName(ctx, projectRoot);
iosPlatformPath = path.join(projectRoot, 'platforms', 'ios');
var wkWebViewPluginPath = path.join(projectRoot, 'plugins', WKWEBVIEW_PLUGIN_NAME);
isWkWebViewEngineUsed = isDirectoryExists(wkWebViewPluginPath) ? 1 : 0;
} | javascript | {
"resource": ""
} |
q26495 | setMacro | train | function setMacro(xcodeProject) {
var configurations = nonComments(xcodeProject.pbxXCBuildConfigurationSection());
var config;
var buildSettings;
for (config in configurations) {
buildSettings = configurations[config].buildSettings;
var preprocessorDefs = buildSettings['GCC_PREPROCESSOR_DEFINITIONS'] ? buildSettings['GCC_PREPROCESSOR_DEFINITIONS'] : [];
if (!preprocessorDefs.length && !isWkWebViewEngineUsed) {
continue;
}
if (!Array.isArray(preprocessorDefs)) {
preprocessorDefs = [preprocessorDefs];
}
var isModified = false;
var injectedDefinition = strFormat('"%s=%d"', WKWEBVIEW_MACRO, isWkWebViewEngineUsed);
preprocessorDefs.forEach(function(item, idx) {
if (item.indexOf(WKWEBVIEW_MACRO) !== -1) {
preprocessorDefs[idx] = injectedDefinition;
isModified = true;
}
});
if (!isModified) {
preprocessorDefs.push(injectedDefinition);
}
if (preprocessorDefs.length === 1) {
buildSettings['GCC_PREPROCESSOR_DEFINITIONS'] = preprocessorDefs[0];
} else {
buildSettings['GCC_PREPROCESSOR_DEFINITIONS'] = preprocessorDefs;
}
}
} | javascript | {
"resource": ""
} |
q26496 | getBuildConfigurationByName | train | function getBuildConfigurationByName(ctx, buildName) {
// load options from the chcpbuild.options file
var chcpBuildOptions = getBuildOptionsFromConfig(ctx);
if (chcpBuildOptions == null) {
return null;
}
var resultConfig = chcpBuildOptions[buildName];
if (!resultConfig) {
return null;
}
// backwards capability
// TODO: remove this in the next versions
if (resultConfig['config-file'] && !resultConfig['config-file']['url']) {
var url = resultConfig['config-file'];
resultConfig['config-file'] = {
'url': url
};
}
return resultConfig;
} | javascript | {
"resource": ""
} |
q26497 | getBuildOptionsFromConfig | train | function getBuildOptionsFromConfig(ctx) {
var chcpBuildOptionsFilePath = path.join(ctx.opts.projectRoot, OPTIONS_FILE_NAME);
return readObjectFromFile(chcpBuildOptionsFilePath);
} | javascript | {
"resource": ""
} |
q26498 | writeJsonAsXml | train | function writeJsonAsXml(jsData, filePath, options) {
var xmlBuilder = new xml2js.Builder(options);
var changedXmlData = xmlBuilder.buildObject(jsData);
var isSaved = true;
try {
fs.writeFileSync(filePath, changedXmlData);
} catch (err) {
console.log(err);
isSaved = false;
}
return isSaved;
} | javascript | {
"resource": ""
} |
q26499 | acceptNode | train | function acceptNode(node) {
var parent = node.parentElement;
var isMath = (parent && parent.getAttribute && parent.getAttribute('class')) ? parent.getAttribute('class').includes('katex') || parent.getAttribute('class').includes('MathJax') : false;
return parent &&
parent.nodeName !== 'SCRIPT' &&
parent.nodeName !== 'STYLE' &&
parent.nodeName !== 'CODE' &&
parent.nodeName !== 'PRE' &&
parent.nodeName !== 'SPAN' &&
parent.nodeName !== 'D-HEADER' &&
parent.nodeName !== 'D-BYLINE' &&
parent.nodeName !== 'D-MATH' &&
parent.nodeName !== 'D-CODE' &&
parent.nodeName !== 'D-BIBLIOGRAPHY' &&
parent.nodeName !== 'D-FOOTER' &&
parent.nodeName !== 'D-APPENDIX' &&
parent.nodeName !== 'D-FRONTMATTER' &&
parent.nodeName !== 'D-TOC' &&
parent.nodeType !== 8 && //comment nodes
!isMath;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.