_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q26300
train
function(protoProps, classProps) { var child = inherits(this, protoProps, classProps); child.extend = this.extend; // a hack required to WSH inherit `toString` method if (protoProps.hasOwnProperty('toString')) child.prototype.toString = protoProps.toString; return child; }
javascript
{ "resource": "" }
q26301
processClassName
train
function processClassName(name, item) { name = transformClassName(name, item, 'element'); name = transformClassName(name, item, 'modifier'); // expand class name // possible values: // * block__element // * block__element_modifier // * block__element_modifier1_modifier2 // * block_modifier var block = '', element = '', modifier = ''; var separators = getSeparators(); if (~name.indexOf(separators.element)) { var elements = name.split(separators.element); block = elements.shift(); var modifiers = elements.pop().split(separators.modifier); elements.push(modifiers.shift()); element = elements.join(separators.element); modifier = modifiers.join(separators.modifier); } else if (~name.indexOf(separators.modifier)) { var blockModifiers = name.split(separators.modifier); block = blockModifiers.shift(); modifier = blockModifiers.join(separators.modifier); } if (block || element || modifier) { if (!block) { block = item.__bem.block; } // inherit parent bem element, if exists // if (item.parent && item.parent.__bem && item.parent.__bem.element) // element = item.parent.__bem.element + separators.element + element; // produce multiple classes var prefix = block; var result = []; if (element) { prefix += separators.element + element; result.push(prefix); } else { result.push(prefix); } if (modifier) { result.push(prefix + separators.modifier + modifier); } if (!item.__bem.block || modifier) { item.__bem.block = block; } item.__bem.element = element; item.__bem.modifier = modifier; return result; } // ...otherwise, return processed or original class name return name; }
javascript
{ "resource": "" }
q26302
transformClassName
train
function transformClassName(name, item, entityType) { var separators = getSeparators(); var reSep = new RegExp('^(' + separators[entityType] + ')+', 'g'); if (reSep.test(name)) { var depth = 0; // parent lookup depth var cleanName = name.replace(reSep, function(str) { depth = str.length / separators[entityType].length; return ''; }); // find donor element var donor = item; while (donor.parent && depth--) { donor = donor.parent; } if (!donor || !donor.__bem) donor = item; if (donor && donor.__bem) { var prefix = donor.__bem.block; // decide if we should inherit element name // if (entityType == 'element') { // var curElem = cleanName.split(separators.modifier, 1)[0]; // if (donor.__bem.element && donor.__bem.element != curElem) // prefix += separators.element + donor.__bem.element; // } if (entityType == 'modifier' && donor.__bem.element) prefix += separators.element + donor.__bem.element; return prefix + separators[entityType] + cleanName; } } return name; }
javascript
{ "resource": "" }
q26303
train
function(title, menu) { return utils.find(menu || this.getMenu(), function(val) { if (val.type == 'action') { if (val.label == title || val.name == title) { return val.name; } } else { return this.getActionNameForMenuTitle(title, val.items); } }, this); }
javascript
{ "resource": "" }
q26304
parseDB
train
function parseDB(data, optimized) { if (typeof data == 'string') { data = JSON.parse(data); } if (!optimized) { data = optimize(data); } vendorsDB = data.vendors; cssDB = data.css; erasDB = data.era; }
javascript
{ "resource": "" }
q26305
optimize
train
function optimize(data) { if (typeof data == 'string') { data = JSON.parse(data); } return { vendors: parseVendors(data), css: parseCSS(data), era: parseEra(data) }; }
javascript
{ "resource": "" }
q26306
parseVendors
train
function parseVendors(data) { var out = {}; Object.keys(data.agents).forEach(function(name) { var agent = data.agents[name]; out[name] = { prefix: agent.prefix, versions: agent.versions }; }); return out; }
javascript
{ "resource": "" }
q26307
parseCSS
train
function parseCSS(data) { var out = {}; var cssCategories = data.cats.CSS; Object.keys(data.data).forEach(function(name) { var section = data.data[name]; if (name in cssSections) { cssSections[name].forEach(function(kw) { out[kw] = section.stats; }); } }); return out; }
javascript
{ "resource": "" }
q26308
parseEra
train
function parseEra(data) { // some runtimes (like Mozilla Rhino) does not preserves // key order so we have to sort values manually return Object.keys(data.eras).sort(function(a, b) { return parseInt(a.substr(1)) - parseInt(b.substr(1)); }); }
javascript
{ "resource": "" }
q26309
getVendorsList
train
function getVendorsList() { var allVendors = Object.keys(vendorsDB); var vendors = prefs.getArray('caniuse.vendors'); if (!vendors || vendors[0] == 'all') { return allVendors; } return intersection(allVendors, vendors); }
javascript
{ "resource": "" }
q26310
getVersionSlice
train
function getVersionSlice() { var era = prefs.get('caniuse.era'); var ix = erasDB.indexOf(era); if (!~ix) { ix = erasDB.indexOf('e-2'); } return ix; }
javascript
{ "resource": "" }
q26311
train
function(property) { if (!prefs.get('caniuse.enabled') || !cssDB || !(property in cssDB)) { return null; } var prefixes = []; var propStats = cssDB[property]; var versions = getVersionSlice(); getVendorsList().forEach(function(vendor) { var vendorVesions = vendorsDB[vendor].versions.slice(versions); for (var i = 0, v; i < vendorVesions.length; i++) { v = vendorVesions[i]; if (!v) { continue; } if (~propStats[vendor][v].indexOf('x')) { prefixes.push(vendorsDB[vendor].prefix); break; } } }); return utils.unique(prefixes).sort(function(a, b) { return b.length - a.length; }); }
javascript
{ "resource": "" }
q26312
train
function(name, options) { if (arguments.length == 2) return createProfile(name, options); else // create profile object only return new OutputProfile(utils.defaults(name || {}, defaultProfile)); }
javascript
{ "resource": "" }
q26313
train
function(name, syntax) { if (!name && syntax) { // search in user resources first var profile = resources.findItem(syntax, 'profile'); if (profile) { name = profile; } } if (!name) { return profiles.plain; } if (name instanceof OutputProfile) { return name; } if (typeof name === 'string' && name.toLowerCase() in profiles) { return profiles[name.toLowerCase()]; } return this.create(name); }
javascript
{ "resource": "" }
q26314
expectedDiff
train
function expectedDiff(expected, computedStyles) { const received = Array.from(computedStyles) .filter(prop => expected[prop]) .reduce( (obj, prop) => Object.assign(obj, {[prop]: computedStyles.getPropertyValue(prop)}), {}, ) const diffOutput = jestDiff( printoutStyles(expected), printoutStyles(received), ) // Remove the "+ Received" annotation because this is a one-way diff return diffOutput.replace(`${chalk.red('+ Received')}\n`, '') }
javascript
{ "resource": "" }
q26315
_flatten
train
function _flatten (arr) { var flat = []; for (var i = 0, n = arr.length; i < n; i++) { flat = flat.concat(arr[i]); } return flat; }
javascript
{ "resource": "" }
q26316
_every
train
function _every (arr, iterator) { for (var i = 0; i < arr.length; i += 1) { if (iterator(arr[i], i, arr) === false) { return; } } }
javascript
{ "resource": "" }
q26317
_asyncEverySeries
train
function _asyncEverySeries (arr, iterator, callback) { if (!arr.length) { return callback(); } var completed = 0; (function iterate() { iterator(arr[completed], function (err) { if (err || err === false) { callback(err); callback = function () {}; } else { completed += 1; if (completed === arr.length) { callback(); } else { iterate(); } } }); })(); }
javascript
{ "resource": "" }
q26318
reportDelete
train
function reportDelete(context, offset, text) { const start = context.getSourceCode().getLocFromIndex(offset); const end = context.getSourceCode().getLocFromIndex(offset + text.length); const range = [offset, offset + text.length]; context.report({ message: 'Delete `{{ code }}`', data: { code: showInvisibles(text) }, loc: { start, end }, fix(fixer) { return fixer.removeRange(range); } }); }
javascript
{ "resource": "" }
q26319
reportReplace
train
function reportReplace(context, offset, deleteText, insertText) { const start = context.getSourceCode().getLocFromIndex(offset); const end = context .getSourceCode() .getLocFromIndex(offset + deleteText.length); const range = [offset, offset + deleteText.length]; context.report({ message: 'Replace `{{ deleteCode }}` with `{{ insertCode }}`', data: { deleteCode: showInvisibles(deleteText), insertCode: showInvisibles(insertText) }, loc: { start, end }, fix(fixer) { return fixer.replaceTextRange(range, insertText); } }); }
javascript
{ "resource": "" }
q26320
isAppInstalled
train
function isAppInstalled(app, prefixes) { return new Promise((resolve) => { if (!(app in prefixes)) { return resolve(false) } Linking.canOpenURL(prefixes[app]) .then((result) => { resolve(!!result) }) .catch(() => resolve(false)) }) }
javascript
{ "resource": "" }
q26321
train
function(r /*, a[, b[, ...]] */) { // Get the arguments as an array but ommit the initial item Array.prototype.slice.call(arguments, 1).forEach(function(a) { if (Array.isArray(r) && Array.isArray(a)) { Array.prototype.push.apply(r, a); } else if (r && (r instanceof Object || typeof r === 'object') && a && (a instanceof Object || typeof a === 'object') && r !== a) { for (var x in a) { r[x] = hello.utils.extend(r[x], a[x]); } } else { if (Array.isArray(a)) { // Clone it a = a.slice(0); } r = a; } }); return r; }
javascript
{ "resource": "" }
q26322
train
function(service) { // Create self, which inherits from its parent var self = Object.create(this); // Inherit the prototype from its parent self.settings = Object.create(this.settings); // Define the default service if (service) { self.settings.default_service = service; } // Create an instance of Events self.utils.Event.call(self); return self; }
javascript
{ "resource": "" }
q26323
train
function(services, options) { var utils = this.utils; if (!services) { return this.services; } // Define provider credentials // Reformat the ID field for (var x in services) {if (services.hasOwnProperty(x)) { if (typeof (services[x]) !== 'object') { services[x] = {id: services[x]}; } }} // Merge services if there already exists some utils.extend(this.services, services); // Update the default settings with this one. if (options) { utils.extend(this.settings, options); // Do this immediatly incase the browser changes the current path. if ('redirect_uri' in options) { this.settings.redirect_uri = utils.url(options.redirect_uri).href; } } return this; }
javascript
{ "resource": "" }
q26324
train
function() { var _this = this; var utils = _this.utils; var error = utils.error; // Create a new promise var promise = utils.Promise(); var p = utils.args({name:'s', options: 'o', callback: 'f'}, arguments); p.options = p.options || {}; // Add callback to events promise.proxy.then(p.callback, p.callback); // Trigger an event on the global listener function emit(s, value) { hello.emit(s, value); } promise.proxy.then(emit.bind(this, 'auth.logout auth'), emit.bind(this, 'error')); // Network p.name = p.name || this.settings.default_service; p.authResponse = utils.store(p.name); if (p.name && !(p.name in _this.services)) { promise.reject(error('invalid_network', 'The network was unrecognized')); } else if (p.name && p.authResponse) { // Define the callback var callback = function(opts) { // Remove from the store utils.store(p.name, null); // Emit events by default promise.fulfill(hello.utils.merge({network:p.name}, opts || {})); }; // Run an async operation to remove the users session var _opts = {}; if (p.options.force) { var logout = _this.services[p.name].logout; if (logout) { // Convert logout to URL string, // If no string is returned, then this function will handle the logout async style if (typeof (logout) === 'function') { logout = logout(callback, p); } // If logout is a string then assume URL and open in iframe. if (typeof (logout) === 'string') { utils.iframe(logout); _opts.force = null; _opts.message = 'Logout success on providers site was indeterminate'; } else if (logout === undefined) { // The callback function will handle the response. return promise.proxy; } } } // Remove local credentials callback(_opts); } else { promise.reject(error('invalid_session', 'There was no session to remove')); } return promise.proxy; }
javascript
{ "resource": "" }
q26325
train
function(opts) { // Remove from the store utils.store(p.name, null); // Emit events by default promise.fulfill(hello.utils.merge({network:p.name}, opts || {})); }
javascript
{ "resource": "" }
q26326
train
function(service) { // If the service doesn't exist service = service || this.settings.default_service; if (!service || !(service in this.services)) { return null; } return this.utils.store(service) || null; }
javascript
{ "resource": "" }
q26327
train
function(url, params, formatFunction) { if (params) { // Set default formatting function formatFunction = formatFunction || encodeURIComponent; // Override the items in the URL which already exist for (var x in params) { var str = '([\\?\\&])' + x + '=[^\\&]*'; var reg = new RegExp(str); if (url.match(reg)) { url = url.replace(reg, '$1' + x + '=' + formatFunction(params[x])); delete params[x]; } } } if (!this.isEmpty(params)) { return url + (url.indexOf('?') > -1 ? '&' : '?') + this.param(params, formatFunction); } return url; }
javascript
{ "resource": "" }
q26328
train
function(node, attr, target) { var n = typeof (node) === 'string' ? document.createElement(node) : node; if (typeof (attr) === 'object') { if ('tagName' in attr) { target = attr; } else { for (var x in attr) {if (attr.hasOwnProperty(x)) { if (typeof (attr[x]) === 'object') { for (var y in attr[x]) {if (attr[x].hasOwnProperty(y)) { n[x][y] = attr[x][y]; }} } else if (x === 'html') { n.innerHTML = attr[x]; } // IE doesn't like us setting methods with setAttribute else if (!/^on/.test(x)) { n.setAttribute(x, attr[x]); } else { n[x] = attr[x]; } }} } } if (target === 'body') { (function self() { if (document.body) { document.body.appendChild(n); } else { setTimeout(self, 16); } })(); } else if (typeof (target) === 'object') { target.appendChild(n); } else if (typeof (target) === 'string') { document.getElementsByTagName(target)[0].appendChild(n); } return n; }
javascript
{ "resource": "" }
q26329
train
function(src) { this.append('iframe', {src: src, style: {position:'absolute', left: '-1000px', bottom: 0, height: '1px', width: '1px'}}, 'body'); }
javascript
{ "resource": "" }
q26330
train
function(path) { // If the path is empty if (!path) { return window.location; } // Chrome and FireFox support new URL() to extract URL objects else if (window.URL && URL instanceof Function && URL.length !== 0) { return new URL(path, window.location); } // Ugly shim, it works! else { var a = document.createElement('a'); a.href = path; return a.cloneNode(false); } }
javascript
{ "resource": "" }
q26331
train
function(a, b) { if (a || !b) { var r = {}; for (var x in a) { // Does the property not exist? if (!(x in b)) { r[x] = a[x]; } } return r; } return a; }
javascript
{ "resource": "" }
q26332
train
function(a) { if (!Array.isArray(a)) { return []; } return a.filter(function(item, index) { // Is this the first location of item return a.indexOf(item) === index; }); }
javascript
{ "resource": "" }
q26333
train
function(callback, guid) { // If the guid has not been supplied then create a new one. guid = guid || '_hellojs_' + parseInt(Math.random() * 1e12, 10).toString(36); // Define the callback function window[guid] = function() { // Trigger the callback try { if (callback.apply(this, arguments)) { delete window[guid]; } } catch (e) { console.error(e); } }; return guid; }
javascript
{ "resource": "" }
q26334
train
function(url, redirectUri, options) { var documentElement = document.documentElement; // Multi Screen Popup Positioning (http://stackoverflow.com/a/16861050) // Credit: http://www.xtf.dk/2011/08/center-new-popup-window-even-on.html // Fixes dual-screen position Most browsers Firefox if (options.height && options.top === undefined) { var dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top; var height = screen.height || window.innerHeight || documentElement.clientHeight; options.top = parseInt((height - options.height) / 2, 10) + dualScreenTop; } if (options.width && options.left === undefined) { var dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left; var width = screen.width || window.innerWidth || documentElement.clientWidth; options.left = parseInt((width - options.width) / 2, 10) + dualScreenLeft; } // Convert options into an array var optionsArray = []; Object.keys(options).forEach(function(name) { var value = options[name]; optionsArray.push(name + (value !== null ? '=' + value : '')); }); // Call the open() function with the initial path // // OAuth redirect, fixes URI fragments from being lost in Safari // (URI Fragments within 302 Location URI are lost over HTTPS) // Loading the redirect.html before triggering the OAuth Flow seems to fix it. // // Firefox decodes URL fragments when calling location.hash. // - This is bad if the value contains break points which are escaped // - Hence the url must be encoded twice as it contains breakpoints. if (navigator.userAgent.indexOf('Safari') !== -1 && navigator.userAgent.indexOf('Chrome') === -1) { url = redirectUri + '#oauth_redirect=' + encodeURIComponent(encodeURIComponent(url)); } var popup = window.open( url, '_blank', optionsArray.join(',') ); if (popup && popup.focus) { popup.focus(); } return popup; }
javascript
{ "resource": "" }
q26335
authCallback
train
function authCallback(obj, window, parent) { var cb = obj.callback; var network = obj.network; // Trigger the callback on the parent _this.store(network, obj); // If this is a page request it has no parent or opener window to handle callbacks if (('display' in obj) && obj.display === 'page') { return; } // Remove from session object if (parent && cb && cb in parent) { try { delete obj.callback; } catch (e) {} // Update store _this.store(network, obj); // Call the globalEvent function on the parent // It's safer to pass back a string to the parent, // Rather than an object/array (better for IE8) var str = JSON.stringify(obj); try { callback(parent, cb)(str); } catch (e) { // Error thrown whilst executing parent callback } } closeWindow(); }
javascript
{ "resource": "" }
q26336
getPath
train
function getPath(url) { // Format the string if it needs it url = url.replace(/\@\{([a-z\_\-]+)(\|.*?)?\}/gi, function(m, key, defaults) { var val = defaults ? defaults.replace(/^\|/, '') : ''; if (key in p.query) { val = p.query[key]; delete p.query[key]; } else if (p.data && key in p.data) { val = p.data[key]; delete p.data[key]; } else if (!defaults) { promise.reject(error('missing_attribute', 'The attribute ' + key + ' is missing from the request')); } return val; }); // Add base if (!url.match(/^https?:\/\//)) { url = o.base + url; } // Define the request URL p.url = url; // Make the HTTP request with the curated request object // CALLBACK HANDLER // @ response object // @ statusCode integer if available utils.request(p, function(r, headers) { // Is this a raw response? if (!p.formatResponse) { // Bad request? error statusCode or otherwise contains an error response vis JSONP? if (typeof headers === 'object' ? (headers.statusCode >= 400) : (typeof r === 'object' && 'error' in r)) { promise.reject(r); } else { promise.fulfill(r); } return; } // Should this be an object if (r === true) { r = {success:true}; } else if (!r) { r = {}; } // The delete callback needs a better response if (p.method === 'delete') { r = (!r || utils.isEmpty(r)) ? {success:true} : r; } // FORMAT RESPONSE? // Does self request have a corresponding formatter if (o.wrap && ((p.path in o.wrap) || ('default' in o.wrap))) { var wrap = (p.path in o.wrap ? p.path : 'default'); var time = (new Date()).getTime(); // FORMAT RESPONSE var b = o.wrap[wrap](r, headers, p); // Has the response been utterly overwritten? // Typically self augments the existing object.. but for those rare occassions if (b) { r = b; } } // Is there a next_page defined in the response? if (r && 'paging' in r && r.paging.next) { // Add the relative path if it is missing from the paging/next path if (r.paging.next[0] === '?') { r.paging.next = p.path + r.paging.next; } // The relative path has been defined, lets markup the handler in the HashFragment else { r.paging.next += '#' + p.path; } } // Dispatch to listeners // Emit events which pertain to the formatted response if (!r || 'error' in r) { promise.reject(r); } else { promise.fulfill(r); } }); }
javascript
{ "resource": "" }
q26337
formatUrl
train
function formatUrl(p, callback) { // Are we signing the request? var sign; // OAuth1 // Remove the token from the query before signing if (p.authResponse && p.authResponse.oauth && parseInt(p.authResponse.oauth.version, 10) === 1) { // OAUTH SIGNING PROXY sign = p.query.access_token; // Remove the access_token delete p.query.access_token; // Enfore use of Proxy p.proxy = true; } // POST body to querystring if (p.data && (p.method === 'get' || p.method === 'delete')) { // Attach the p.data to the querystring. _this.extend(p.query, p.data); p.data = null; } // Construct the path var path = _this.qs(p.url, p.query); // Proxy the request through a server // Used for signing OAuth1 // And circumventing services without Access-Control Headers if (p.proxy) { // Use the proxy as a path path = _this.qs(p.oauth_proxy, { path: path, access_token: sign || '', // This will prompt the request to be signed as though it is OAuth1 then: p.proxy_response_type || (p.method.toLowerCase() === 'get' ? 'redirect' : 'proxy'), method: p.method.toLowerCase(), suppress_response_codes: true }); } callback(path); }
javascript
{ "resource": "" }
q26338
train
function(type, data) { var test = 'HTML' + (type || '').replace( /^[a-z]/, function(m) { return m.toUpperCase(); } ) + 'Element'; if (!data) { return false; } if (window[test]) { return data instanceof window[test]; } else if (window.Element) { return data instanceof window.Element && (!type || (data.tagName && data.tagName.toLowerCase() === type)); } else { return (!(data instanceof Object || data instanceof Array || data instanceof String || data instanceof Number) && data.tagName && data.tagName.toLowerCase() === type); } }
javascript
{ "resource": "" }
q26339
train
function(obj) { // Does not clone DOM elements, nor Binary data, e.g. Blobs, Filelists if (obj === null || typeof (obj) !== 'object' || obj instanceof Date || 'nodeName' in obj || this.isBinary(obj) || (typeof FormData === 'function' && obj instanceof FormData)) { return obj; } if (Array.isArray(obj)) { // Clone each item in the array return obj.map(this.clone.bind(this)); } // But does clone everything else. var clone = {}; for (var x in obj) { clone[x] = this.clone(obj[x]); } return clone; }
javascript
{ "resource": "" }
q26340
headersToJSON
train
function headersToJSON(s) { var r = {}; var reg = /([a-z\-]+):\s?(.*);?/gi; var m; while ((m = reg.exec(s))) { r[m[1]] = m[2]; } return r; }
javascript
{ "resource": "" }
q26341
train
function(url, callback, callbackID, timeout) { var _this = this; var error = _this.error; // Change the name of the callback var bool = 0; var head = document.getElementsByTagName('head')[0]; var operaFix; var result = error('server_error', 'server_error'); var cb = function() { if (!(bool++)) { window.setTimeout(function() { callback(result); head.removeChild(script); }, 0); } }; // Add callback to the window object callbackID = _this.globalEvent(function(json) { result = json; return true; // Mark callback as done }, callbackID); // The URL is a function for some cases and as such // Determine its value with a callback containing the new parameters of this function. url = url.replace(new RegExp('=\\?(&|$)'), '=' + callbackID + '$1'); // Build script tag var script = _this.append('script', { id: callbackID, name: callbackID, src: url, async: true, onload: cb, onerror: cb, onreadystatechange: function() { if (/loaded|complete/i.test(this.readyState)) { cb(); } } }); // Opera fix error // Problem: If an error occurs with script loading Opera fails to trigger the script.onerror handler we specified // // Fix: // By setting the request to synchronous we can trigger the error handler when all else fails. // This action will be ignored if we've already called the callback handler "cb" with a successful onload event if (window.navigator.userAgent.toLowerCase().indexOf('opera') > -1) { operaFix = _this.append('script', { text: 'document.getElementById(\'' + callbackID + '\').onerror();' }); script.async = false; } // Add timeout if (timeout) { window.setTimeout(function() { result = error('timeout', 'timeout'); cb(); }, timeout); } // TODO: add fix for IE, // However: unable recreate the bug of firing off the onreadystatechange before the script content has been executed and the value of "result" has been defined. // Inject script tag into the head element head.appendChild(script); // Append Opera Fix to run after our script if (operaFix) { head.appendChild(operaFix); } }
javascript
{ "resource": "" }
q26342
train
function(data) { for (var x in data) if (data.hasOwnProperty(x)) { if (this.isBinary(data[x])) { return true; } } return false; }
javascript
{ "resource": "" }
q26343
train
function(data) { return data instanceof Object && ( (this.domInstance('input', data) && data.type === 'file') || ('FileList' in window && data instanceof window.FileList) || ('File' in window && data instanceof window.File) || ('Blob' in window && data instanceof window.Blob)); }
javascript
{ "resource": "" }
q26344
train
function(p) { var _this = this; var w = window; var data = p.data; // Is data a form object if (_this.domInstance('form', data)) { data = _this.nodeListToJSON(data.elements); } else if ('NodeList' in w && data instanceof NodeList) { data = _this.nodeListToJSON(data); } else if (_this.domInstance('input', data)) { data = _this.nodeListToJSON([data]); } // Is data a blob, File, FileList? if (('File' in w && data instanceof w.File) || ('Blob' in w && data instanceof w.Blob) || ('FileList' in w && data instanceof w.FileList)) { data = {file: data}; } // Loop through data if it's not form data it must now be a JSON object if (!('FormData' in w && data instanceof w.FormData)) { for (var x in data) if (data.hasOwnProperty(x)) { if ('FileList' in w && data[x] instanceof w.FileList) { if (data[x].length === 1) { data[x] = data[x][0]; } } else if (_this.domInstance('input', data[x]) && data[x].type === 'file') { continue; } else if (_this.domInstance('input', data[x]) || _this.domInstance('select', data[x]) || _this.domInstance('textArea', data[x])) { data[x] = data[x].value; } else if (_this.domInstance(null, data[x])) { data[x] = data[x].innerHTML || data[x].innerText; } } } p.data = data; return data; }
javascript
{ "resource": "" }
q26345
train
function(nodelist) { var json = {}; // Create a data string for (var i = 0; i < nodelist.length; i++) { var input = nodelist[i]; // If the name of the input is empty or diabled, dont add it. if (input.disabled || !input.name) { continue; } // Is this a file, does the browser not support 'files' and 'FormData'? if (input.type === 'file') { json[input.name] = input; } else { json[input.name] = input.value || input.innerHTML; } } return json; }
javascript
{ "resource": "" }
q26346
train
function(p) { // The proxy supports allow-cross-origin-resource // Alas that's the only thing we're using. if (p.data && p.data.file) { var file = p.data.file; if (file) { if (file.files) { p.data = file.files[0]; } else { p.data = file; } } } if (p.method === 'delete') { p.method = 'post'; } return true; }
javascript
{ "resource": "" }
q26347
train
function(p, qs) { if (p.method === 'get' || p.method === 'post') { qs.suppress_response_codes = true; } // Is this a post with a data-uri? if (p.method === 'post' && p.data && typeof (p.data.file) === 'string') { // Convert the Data-URI to a Blob p.data.file = hello.utils.toBlob(p.data.file); } return true; }
javascript
{ "resource": "" }
q26348
train
function(p, qs) { var m = p.method; if (m !== 'get' && !hello.utils.hasBinary(p.data)) { p.data.method = m; p.method = 'get'; } else if (p.method === 'delete') { qs.method = 'delete'; p.method = 'post'; } }
javascript
{ "resource": "" }
q26349
withUser
train
function withUser(cb) { var auth = hello.getAuthResponse('flickr'); cb(auth && auth.user_nsid ? auth.user_nsid : null); }
javascript
{ "resource": "" }
q26350
gEntry
train
function gEntry(o) { paging(o); if ('feed' in o && 'entry' in o.feed) { o.data = o.feed.entry.map(formatEntry); delete o.feed; } // Old style: Picasa, etc. else if ('entry' in o) { return formatEntry(o.entry); } // New style: Google Drive else if ('items' in o) { o.data = o.items.map(formatItem); delete o.items; } else { formatItem(o); } return o; }
javascript
{ "resource": "" }
q26351
Multipart
train
function Multipart() { // Internal body var body = []; var boundary = (Math.random() * 1e10).toString(32); var counter = 0; var lineBreak = '\r\n'; var delim = lineBreak + '--' + boundary; var ready = function() {}; var dataUri = /^data\:([^;,]+(\;charset=[^;,]+)?)(\;base64)?,/i; // Add file function addFile(item) { var fr = new FileReader(); fr.onload = function(e) { addContent(btoa(e.target.result), item.type + lineBreak + 'Content-Transfer-Encoding: base64'); }; fr.readAsBinaryString(item); } // Add content function addContent(content, type) { body.push(lineBreak + 'Content-Type: ' + type + lineBreak + lineBreak + content); counter--; ready(); } // Add new things to the object this.append = function(content, type) { // Does the content have an array if (typeof (content) === 'string' || !('length' in Object(content))) { // Converti to multiples content = [content]; } for (var i = 0; i < content.length; i++) { counter++; var item = content[i]; // Is this a file? // Files can be either Blobs or File types if ( (typeof (File) !== 'undefined' && item instanceof File) || (typeof (Blob) !== 'undefined' && item instanceof Blob) ) { // Read the file in addFile(item); } // Data-URI? // Data:[<mime type>][;charset=<charset>][;base64],<encoded data> // /^data\:([^;,]+(\;charset=[^;,]+)?)(\;base64)?,/i else if (typeof (item) === 'string' && item.match(dataUri)) { var m = item.match(dataUri); addContent(item.replace(dataUri, ''), m[1] + lineBreak + 'Content-Transfer-Encoding: base64'); } // Regular string else { addContent(item, type); } } }; this.onready = function(fn) { ready = function() { if (counter === 0) { // Trigger ready body.unshift(''); body.push('--'); fn(body.join(delim), boundary); body = []; } }; ready(); }; }
javascript
{ "resource": "" }
q26352
train
function(p, qs) { var method = p.method; var proxy = method !== 'get'; if (proxy) { if ((method === 'post' || method === 'put') && p.query.access_token) { p.data.access_token = p.query.access_token; delete p.query.access_token; } // No access control headers // Use the proxy instead p.proxy = proxy; } return proxy; }
javascript
{ "resource": "" }
q26353
formatRequest
train
function formatRequest(p, qs) { var token = qs.access_token; delete qs.access_token; p.headers.Authorization = 'Bearer ' + token; return true; }
javascript
{ "resource": "" }
q26354
getSizeInPixels
train
function getSizeInPixels(el, value) { if (/px$/i.test(value)) return parseFloat(value); var style = el.style.left, runtimeStyle = el.runtimeStyle.left; el.runtimeStyle.left = el.currentStyle.left; el.style.left = value; var result = el.style.pixelLeft; el.style.left = style; el.runtimeStyle.left = runtimeStyle; return result; }
javascript
{ "resource": "" }
q26355
train
function(eventName, handler) { if (!this.__eventListeners) { this.__eventListeners = { }; } // one object with key/value pairs was passed if (arguments.length === 1) { for (var prop in eventName) { this.on(prop, eventName[prop]); } } else { if (!this.__eventListeners[eventName]) { this.__eventListeners[eventName] = [ ]; } this.__eventListeners[eventName].push(handler); } }
javascript
{ "resource": "" }
q26356
train
function(eventName, handler) { if (!this.__eventListeners) { this.__eventListeners = { }; } if (this.__eventListeners[eventName]) { fabric.util.removeFromArray(this.__eventListeners[eventName], handler); } }
javascript
{ "resource": "" }
q26357
train
function(eventName, options) { if (!this.__eventListeners) { this.__eventListeners = { } } var listenersForEvent = this.__eventListeners[eventName]; if (!listenersForEvent) return; for (var i = 0, len = listenersForEvent.length; i < len; i++) { // avoiding try/catch for perf. reasons listenersForEvent[i](options || { }); } }
javascript
{ "resource": "" }
q26358
animate
train
function animate(options) { options || (options = { }); var start = +new Date(), duration = options.duration || 500, finish = start + duration, time, pos, onChange = options.onChange || function() { }, abort = options.abort || function() { return false; }, easing = options.easing || function(t, b, c, d) {return -c * Math.cos(t/d * (Math.PI/2)) + c + b;}, startValue = 'startValue' in options ? options.startValue : 0, endValue = 'endValue' in options ? options.endValue : 100; byValue = options.byValue || endValue - startValue; options.onStart && options.onStart(); (function tick() { time = +new Date(); currentTime = time > finish ? duration : (time - start); onChange(easing(currentTime, startValue, byValue, duration)); if (time > finish || abort()) { options.onComplete && options.onComplete(); return; } requestAnimFrame(tick); })(); }
javascript
{ "resource": "" }
q26359
loadImage
train
function loadImage(url, callback, context) { if (url) { var img = new Image(); /** @ignore */ img.onload = function () { callback && callback.call(context, img); img = img.onload = null; }; img.src = url; } else { callback && callback.call(context, url); } }
javascript
{ "resource": "" }
q26360
invoke
train
function invoke(array, method) { var args = slice.call(arguments, 2), result = [ ]; for (var i = 0, len = array.length; i < len; i++) { result[i] = args.length ? array[i][method].apply(array[i], args) : array[i][method].call(array[i]); } return result; }
javascript
{ "resource": "" }
q26361
camelize
train
function camelize(string) { return string.replace(/-+(.)?/g, function(match, character) { return character ? character.toUpperCase() : ''; }); }
javascript
{ "resource": "" }
q26362
createClass
train
function createClass() { var parent = null, properties = slice.call(arguments, 0); if (typeof properties[0] === 'function') { parent = properties.shift(); } function klass() { this.initialize.apply(this, arguments); } klass.superclass = parent; klass.subclasses = [ ]; if (parent) { subclass.prototype = parent.prototype; klass.prototype = new subclass; parent.subclasses.push(klass); } for (var i = 0, length = properties.length; i < length; i++) { addMethods(klass, properties[i], parent); } if (!klass.prototype.initialize) { klass.prototype.initialize = emptyFunction; } klass.prototype.constructor = klass; return klass; }
javascript
{ "resource": "" }
q26363
setStyle
train
function setStyle(element, styles) { var elementStyle = element.style, match; if (!elementStyle) { return element; } if (typeof styles === 'string') { element.style.cssText += ';' + styles; return styles.indexOf('opacity') > -1 ? setOpacity(element, styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element; } for (var property in styles) { if (property === 'opacity') { setOpacity(element, styles[property]); } else { var normalizedProperty = (property === 'float' || property === 'cssFloat') ? (typeof elementStyle.styleFloat === 'undefined' ? 'cssFloat' : 'styleFloat') : property; elementStyle[normalizedProperty] = styles[property]; } } return element; }
javascript
{ "resource": "" }
q26364
makeElement
train
function makeElement(tagName, attributes) { var el = fabric.document.createElement(tagName); for (var prop in attributes) { if (prop === 'class') { el.className = attributes[prop]; } else if (prop === 'for') { el.htmlFor = attributes[prop]; } else { el.setAttribute(prop, attributes[prop]); } } return el; }
javascript
{ "resource": "" }
q26365
addClass
train
function addClass(element, className) { if ((' ' + element.className + ' ').indexOf(' ' + className + ' ') === -1) { element.className += (element.className ? ' ' : '') + className; } }
javascript
{ "resource": "" }
q26366
wrapElement
train
function wrapElement(element, wrapper, attributes) { if (typeof wrapper === 'string') { wrapper = makeElement(wrapper, attributes); } if (element.parentNode) { element.parentNode.replaceChild(wrapper, element); } wrapper.appendChild(element); return wrapper; }
javascript
{ "resource": "" }
q26367
makeElementUnselectable
train
function makeElementUnselectable(element) { if (typeof element.onselectstart !== 'undefined') { element.onselectstart = fabric.util.falseFunction; } if (selectProp) { element.style[selectProp] = 'none'; } else if (typeof element.unselectable == 'string') { element.unselectable = 'on'; } return element; }
javascript
{ "resource": "" }
q26368
makeElementSelectable
train
function makeElementSelectable(element) { if (typeof element.onselectstart !== 'undefined') { element.onselectstart = null; } if (selectProp) { element.style[selectProp] = ''; } else if (typeof element.unselectable == 'string') { element.unselectable = ''; } return element; }
javascript
{ "resource": "" }
q26369
request
train
function request(url, options) { options || (options = { }); var method = options.method ? options.method.toUpperCase() : 'GET', onComplete = options.onComplete || function() { }, request = makeXHR(), body; /** @ignore */ request.onreadystatechange = function() { if (request.readyState === 4) { onComplete(request); request.onreadystatechange = emptyFn; } }; if (method === 'GET') { body = null; if (typeof options.parameters == 'string') { url = addParamToUrl(url, options.parameters); } } request.open(method, url, true); if (method === 'POST' || method === 'PUT') { request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); } request.send(body); return request; }
javascript
{ "resource": "" }
q26370
parsePointsAttribute
train
function parsePointsAttribute(points) { // points attribute is required and must not be empty if (!points) return null; points = points.trim(); var asPairs = points.indexOf(',') > -1; points = points.split(/\s+/); var parsedPoints = [ ]; // points could look like "10,20 30,40" or "10 20 30 40" if (asPairs) { for (var i = 0, len = points.length; i < len; i++) { var pair = points[i].split(','); parsedPoints.push({ x: parseFloat(pair[0]), y: parseFloat(pair[1]) }); } } else { for (var i = 0, len = points.length; i < len; i+=2) { parsedPoints.push({ x: parseFloat(points[i]), y: parseFloat(points[i+1]) }); } } // odd number of points is an error if (parsedPoints.length % 2 !== 0) { // return null; } return parsedPoints; }
javascript
{ "resource": "" }
q26371
parseStyleAttribute
train
function parseStyleAttribute(element) { var oStyle = { }, style = element.getAttribute('style'); if (style) { if (typeof style == 'string') { style = style.replace(/;$/, '').split(';').forEach(function (current) { var attr = current.split(':'); oStyle[normalizeAttr(attr[0].trim().toLowerCase())] = attr[1].trim(); }); } else { for (var prop in style) { if (typeof style[prop] !== 'undefined') { oStyle[normalizeAttr(prop.toLowerCase())] = style[prop]; } } } } return oStyle; }
javascript
{ "resource": "" }
q26372
getCSSRules
train
function getCSSRules(doc) { var styles = doc.getElementsByTagName('style'), allRules = { }, rules; // very crude parsing of style contents for (var i = 0, len = styles.length; i < len; i++) { var styleContents = styles[0].textContent; // remove comments styleContents = styleContents.replace(/\/\*[\s\S]*?\*\//g, ''); rules = styleContents.match(/[^{]*\{[\s\S]*?\}/g); rules = rules.map(function(rule) { return rule.trim() }); rules.forEach(function(rule) { var match = rule.match(/([\s\S]*?)\s*\{([^}]*)\}/), rule = match[1], declaration = match[2].trim(), propertyValuePairs = declaration.replace(/;$/, '').split(/\s*;\s*/); if (!allRules[rule]) { allRules[rule] = { }; } for (var i = 0, len = propertyValuePairs.length; i < len; i++) { var pair = propertyValuePairs[i].split(/\s*:\s*/), property = pair[0], value = pair[1]; allRules[rule][property] = value; } }); } return allRules; }
javascript
{ "resource": "" }
q26373
loadSVGFromURL
train
function loadSVGFromURL(url, callback, reviver) { url = url.replace(/^\n\s*/, '').trim(); svgCache.has(url, function (hasUrl) { if (hasUrl) { svgCache.get(url, function (value) { var enlivedRecord = _enlivenCachedObject(value); callback(enlivedRecord.objects, enlivedRecord.options); }); } else { new fabric.util.request(url, { method: 'get', onComplete: onComplete }); } }); function onComplete(r) { var xml = r.responseXML; if (!xml.documentElement && fabric.window.ActiveXObject && r.responseText) { xml = new ActiveXObject('Microsoft.XMLDOM'); xml.async = 'false'; //IE chokes on DOCTYPE xml.loadXML(r.responseText.replace(/<!DOCTYPE[\s\S]*?(\[[\s\S]*\])*?>/i,'')); } if (!xml.documentElement) return; fabric.parseSVGDocument(xml.documentElement, function (results, options) { svgCache.set(url, { objects: fabric.util.array.invoke(results, 'toObject'), options: options }); callback(results, options); }, reviver); } }
javascript
{ "resource": "" }
q26374
loadSVGFromString
train
function loadSVGFromString(string, callback, reviver) { string = string.trim(); var doc; if (typeof DOMParser !== 'undefined') { var parser = new DOMParser(); if (parser && parser.parseFromString) { doc = parser.parseFromString(string, 'text/xml'); } } else if (fabric.window.ActiveXObject) { var doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = 'false'; //IE chokes on DOCTYPE doc.loadXML(string.replace(/<!DOCTYPE[\s\S]*?(\[[\s\S]*\])*?>/i,'')); } fabric.parseSVGDocument(doc.documentElement, function (results, options) { callback(results, options); }, reviver); }
javascript
{ "resource": "" }
q26375
getGradientDefs
train
function getGradientDefs(doc) { var linearGradientEls = doc.getElementsByTagName('linearGradient'), radialGradientEls = doc.getElementsByTagName('radialGradient'), el, gradientDefs = { }; for (var i = linearGradientEls.length; i--; ) { el = linearGradientEls[i]; gradientDefs[el.getAttribute('id')] = el; } for (var i = radialGradientEls.length; i--; ) { el = radialGradientEls[i]; gradientDefs[el.getAttribute('id')] = el; } return gradientDefs; }
javascript
{ "resource": "" }
q26376
train
function() { var source = this.getSource(); var r = source[0].toString(16); r = (r.length == 1) ? ('0' + r) : r; var g = source[1].toString(16); g = (g.length == 1) ? ('0' + g) : g; var b = source[2].toString(16); b = (b.length == 1) ? ('0' + b) : b; return r.toUpperCase() + g.toUpperCase() + b.toUpperCase(); }
javascript
{ "resource": "" }
q26377
train
function() { var source = this.getSource(), average = parseInt((source[0] * 0.3 + source[1] * 0.59 + source[2] * 0.11).toFixed(0), 10), currentAlpha = source[3]; this.setSource([average, average, average, currentAlpha]); return this; }
javascript
{ "resource": "" }
q26378
train
function(threshold) { var source = this.getSource(), average = (source[0] * 0.3 + source[1] * 0.59 + source[2] * 0.11).toFixed(0), currentAlpha = source[3], threshold = threshold || 127; average = (Number(average) < Number(threshold)) ? 0 : 255; this.setSource([average, average, average, currentAlpha]); return this; }
javascript
{ "resource": "" }
q26379
train
function(otherColor) { if (!(otherColor instanceof Color)) { otherColor = new Color(otherColor); } var result = [], alpha = this.getAlpha(), otherAlpha = 0.5, source = this.getSource(), otherSource = otherColor.getSource(); for (var i = 0; i < 3; i++) { result.push(Math.round((source[i] * (1 - otherAlpha)) + (otherSource[i] * otherAlpha))); } result[3] = alpha; this.setSource(result); return this; }
javascript
{ "resource": "" }
q26380
train
function (url, callback) { // TODO (kangax): test callback fabric.util.loadImage(url, function(img) { this.overlayImage = img; callback && callback(); }, this); return this; }
javascript
{ "resource": "" }
q26381
train
function (url, callback, options) { return fabric.util.loadImage(url, function(img) { this.backgroundImage = img; if (options && ('backgroundImageOpacity' in options)) { this.backgroundImageOpacity = options.backgroundImageOpacity; } if (options && ('backgroundImageStretch' in options)) { this.backgroundImageStretch = options.backgroundImageStretch; } callback && callback(); }, this); }
javascript
{ "resource": "" }
q26382
train
function (canvasEl) { this.lowerCanvasEl = fabric.util.getById(canvasEl) || this._createCanvasElement(); this._initCanvasElement(this.lowerCanvasEl); fabric.util.addClass(this.lowerCanvasEl, 'lower-canvas'); if (this.interactive) { this._applyCanvasStyle(this.lowerCanvasEl); } this.contextContainer = this.lowerCanvasEl.getContext('2d'); }
javascript
{ "resource": "" }
q26383
train
function (ctx, object) { if (!object) return; if (this.controlsAboveOverlay) { var hasBorders = object.hasBorders, hasCorners = object.hasCorners; object.hasBorders = object.hasCorners = false; object.render(ctx); object.hasBorders = hasBorders; object.hasCorners = hasCorners; } else { object.render(ctx); } }
javascript
{ "resource": "" }
q26384
train
function (allOnTop) { var canvasToDrawOn = this[(allOnTop === true && this.interactive) ? 'contextTop' : 'contextContainer']; if (this.contextTop) { this.clearContext(this.contextTop); } if (allOnTop === false || (typeof allOnTop === 'undefined')) { this.clearContext(canvasToDrawOn); } var length = this._objects.length, activeGroup = this.getActiveGroup(), startTime = new Date(); if (this.clipTo) { canvasToDrawOn.save(); canvasToDrawOn.beginPath(); this.clipTo(canvasToDrawOn); canvasToDrawOn.clip(); } canvasToDrawOn.fillStyle = this.backgroundColor; canvasToDrawOn.fillRect(0, 0, this.width, this.height); if (typeof this.backgroundImage == 'object') { canvasToDrawOn.save(); canvasToDrawOn.globalAlpha = this.backgroundImageOpacity; if (this.backgroundImageStretch) { canvasToDrawOn.drawImage(this.backgroundImage, 0, 0, this.width, this.height); } else { canvasToDrawOn.drawImage(this.backgroundImage, 0, 0); } canvasToDrawOn.restore(); } if (length) { for (var i = 0; i < length; ++i) { if (!activeGroup || (activeGroup && this._objects[i] && !activeGroup.contains(this._objects[i]))) { this._draw(canvasToDrawOn, this._objects[i]); } } } if (this.clipTo) { canvasToDrawOn.restore(); } // delegate rendering to group selection (if one exists) if (activeGroup) { this._draw(this.contextTop, activeGroup); } if (this.overlayImage) { this.contextContainer.drawImage(this.overlayImage, 0, 0); } if (this.controlsAboveOverlay) { this.drawControls(this.contextContainer); } if (this.onFpsUpdate) { var elapsedTime = new Date() - startTime; this.onFpsUpdate(~~(1000 / elapsedTime)); } this.fire('after:render'); return this; }
javascript
{ "resource": "" }
q26385
train
function () { this.clearContext(this.contextTop || this.contextContainer); if (this.overlayImage) { this.contextContainer.drawImage(this.overlayImage, 0, 0); } // we render the top context - last object if (this.selection && this._groupSelector) { this._drawSelection(); } // delegate rendering to group selection if one exists // used for drawing selection borders/corners var activeGroup = this.getActiveGroup(); if (activeGroup) { activeGroup.render(this.contextTop); } this.fire('after:render'); return this; }
javascript
{ "resource": "" }
q26386
train
function (format, quality) { var canvasEl = this.upperCanvasEl || this.lowerCanvasEl; this.renderAll(true); var data = (fabric.StaticCanvas.supports('toDataURLWithQuality')) ? canvasEl.toDataURL('image/' + format, quality) : canvasEl.toDataURL('image/' + format); this.renderAll(); return data; }
javascript
{ "resource": "" }
q26387
train
function() { var markup = [ '<?xml version="1.0" standalone="no" ?>', '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN" ', '"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">', '<svg ', 'xmlns="http://www.w3.org/2000/svg" ', 'xmlns:xlink="http://www.w3.org/1999/xlink" ', 'version="1.1" ', 'width="', this.width, '" ', 'height="', this.height, '" ', 'xml:space="preserve">', '<desc>Created with Fabric.js ', fabric.version, '</desc>', fabric.createSVGFontFacesMarkup(this.getObjects()) ]; if (this.backgroundImage) { markup.push( '<image x="0" y="0" ', 'width="', this.width, '" height="', this.height, '" preserveAspectRatio="', (this.backgroundImageStretch ? 'none' : 'defer'), '" xlink:href="', this.backgroundImage.src, '" style="opacity:', this.backgroundImageOpacity, '"></image>' ); } for (var i = 0, objects = this.getObjects(), len = objects.length; i < len; i++) { markup.push(objects[i].toSVG()); } markup.push('</svg>'); return markup.join(''); }
javascript
{ "resource": "" }
q26388
train
function (object) { removeFromArray(this._objects, object); if (this.getActiveObject() === object) { // removing active object should fire "selection:cleared" events this.fire('before:selection:cleared', { target: object }); this.discardActiveObject(); this.fire('selection:cleared'); } this.renderAll(); return object; }
javascript
{ "resource": "" }
q26389
train
function (object) { var idx = this._objects.indexOf(object), nextIntersectingIdx = idx; // if object is not on the bottom of stack if (idx !== 0) { // traverse down the stack looking for the nearest intersecting object for (var i=idx-1; i>=0; --i) { if (object.intersectsWithObject(this._objects[i]) || object.isContainedWithinObject(this._objects[i])) { nextIntersectingIdx = i; break; } } removeFromArray(this._objects, object); this._objects.splice(nextIntersectingIdx, 0, object); } return this.renderAll(); }
javascript
{ "resource": "" }
q26390
train
function (object) { var objects = this.getObjects(), idx = objects.indexOf(object), nextIntersectingIdx = idx; // if object is not on top of stack (last item in an array) if (idx !== objects.length-1) { // traverse up the stack looking for the nearest intersecting object for (var i = idx + 1, l = this._objects.length; i < l; ++i) { if (object.intersectsWithObject(objects[i]) || object.isContainedWithinObject(this._objects[i])) { nextIntersectingIdx = i; break; } } removeFromArray(objects, object); objects.splice(nextIntersectingIdx, 0, object); } this.renderAll(); }
javascript
{ "resource": "" }
q26391
train
function () { return this.getObjects().reduce(function (memo, current) { memo += current.complexity ? current.complexity() : 0; return memo; }, 0); }
javascript
{ "resource": "" }
q26392
train
function(callback, context) { var objects = this.getObjects(), i = objects.length; while (i--) { callback.call(context, objects[i], i, objects); } return this; }
javascript
{ "resource": "" }
q26393
train
function () { this.clear(); if (this.interactive) { removeListener(this.upperCanvasEl, 'mousedown', this._onMouseDown); removeListener(this.upperCanvasEl, 'mousemove', this._onMouseMove); removeListener(fabric.window, 'resize', this._onResize); } return this; }
javascript
{ "resource": "" }
q26394
train
function () { var _this = this; this._onMouseDown = function (e) { _this.__onMouseDown(e); addListener(fabric.document, 'mouseup', _this._onMouseUp); fabric.isTouchSupported && addListener(fabric.document, 'touchend', _this._onMouseUp); addListener(fabric.document, 'mousemove', _this._onMouseMove); fabric.isTouchSupported && addListener(fabric.document, 'touchmove', _this._onMouseMove); removeListener(_this.upperCanvasEl, 'mousemove', _this._onMouseMove); fabric.isTouchSupported && removeListener(_this.upperCanvasEl, 'touchmove', _this._onMouseMove); }; this._onMouseUp = function (e) { _this.__onMouseUp(e); removeListener(fabric.document, 'mouseup', _this._onMouseUp); fabric.isTouchSupported && removeListener(fabric.document, 'touchend', _this._onMouseUp); removeListener(fabric.document, 'mousemove', _this._onMouseMove); fabric.isTouchSupported && removeListener(fabric.document, 'touchmove', _this._onMouseMove); addListener(_this.upperCanvasEl, 'mousemove', _this._onMouseMove); fabric.isTouchSupported && addListener(_this.upperCanvasEl, 'touchmove', _this._onMouseMove); }; this._onMouseMove = function (e) { e.preventDefault && e.preventDefault(); _this.__onMouseMove(e); }; this._onResize = function (e) { _this.calcOffset(); }; addListener(fabric.window, 'resize', this._onResize); if (fabric.isTouchSupported) { addListener(this.upperCanvasEl, 'touchstart', this._onMouseDown); addListener(this.upperCanvasEl, 'touchmove', this._onMouseMove); } else { addListener(this.upperCanvasEl, 'mousedown', this._onMouseDown); addListener(this.upperCanvasEl, 'mousemove', this._onMouseMove); } }
javascript
{ "resource": "" }
q26395
train
function (e, target) { var pointer = this.getPointer(e), xy = this._normalizePointer(target, pointer), x = xy.x, y = xy.y; // http://www.geog.ubc.ca/courses/klink/gis.notes/ncgia/u32.html // http://idav.ucdavis.edu/~okreylos/TAship/Spring2000/PointInPolygon.html // we iterate through each object. If target found, return it. var iLines = target._getImageLines(target.oCoords), xpoints = target._findCrossPoints(x, y, iLines); // if xcount is odd then we clicked inside the object // For the specific case of square images xcount === 1 in all true cases if ((xpoints && xpoints % 2 === 1) || target._findTargetCorner(e, this._offset)) { return true; } return false; }
javascript
{ "resource": "" }
q26396
train
function (x, y) { var t = this._currentTransform, o = this._offset; if (t.target.lockRotation) return; var lastAngle = atan2(t.ey - t.top - o.top, t.ex - t.left - o.left), curAngle = atan2(y - t.top - o.top, x - t.left - o.left); t.target._theta = (curAngle - lastAngle) + t.theta; }
javascript
{ "resource": "" }
q26397
train
function (e, skipGroup) { var target, pointer = this.getPointer(e); // first check current group (if one exists) var activeGroup = this.getActiveGroup(); if (activeGroup && !skipGroup && this.containsPoint(e, activeGroup)) { target = activeGroup; return target; } // then check all of the objects on canvas // Cache all targets where their bounding box contains point. var possibleTargets = []; for (var i = this._objects.length; i--; ) { if (this._objects[i] && this.containsPoint(e, this._objects[i])) { if (this.perPixelTargetFind || this._objects[i].perPixelTargetFind) { possibleTargets[possibleTargets.length] = this._objects[i]; } else { target = this._objects[i]; this.relatedTarget = target; break; } } } for (var i = 0, len = possibleTargets.length; i < len; i++) { var pointer = this.getPointer(e); var isTransparent = this._isTargetTransparent(possibleTargets[i], pointer.x, pointer.y); if (!isTransparent) { target = possibleTargets[i]; this.relatedTarget = target; break; } } if (target && target.selectable) { return target; } }
javascript
{ "resource": "" }
q26398
train
function (e) { var pointer = getPointer(e); return { x: pointer.x - this._offset.left, y: pointer.y - this._offset.top }; }
javascript
{ "resource": "" }
q26399
train
function (object, e) { if (this._activeObject) { this._activeObject.setActive(false); } this._activeObject = object; object.setActive(true); this.renderAll(); this.fire('object:selected', { target: object, e: e }); object.fire('selected', { e: e }); return this; }
javascript
{ "resource": "" }