_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q35400 | train | function (filename, arg, callback) {
console.log('*** git-hooks.js run', filename, arg);
var hookName = path.basename(filename);
var hooksDirname = path.resolve(path.dirname(filename), '../../.githooks', hookName);
if (fsHelpers.exists(hooksDirname)) {
var list = fs.readdirSync(hooksDirname);
var hooks = list.map(function (hookName) {
return path.resolve(hooksDirname, hookName);
});
excludeIgnoredPaths(hooks, function (filteredHooks) {
runHooks(filteredHooks, [arg], callback);
});
} else {
callback(0);
}
} | javascript | {
"resource": ""
} | |
q35401 | runHooks | train | function runHooks(hooks, args, callback) {
console.log('*** git-hooks.js runHooks', hooks, args);
if (!hooks.length) {
callback(0);
return;
}
try {
var hook = spawnHook(hooks.shift(), args);
hook.on('close', function (code) {
if (code === 0) {
runHooks(hooks, args, callback);
} else {
callback(code);
}
});
} catch (e) {
callback(1, e);
}
} | javascript | {
"resource": ""
} |
q35402 | train | function () {
if (this._duration) {
return this._duration;
}
if (this._start && this._end) {
return moment.duration(this._end - this._start);
}
else {
return moment.duration(0);
}
} | javascript | {
"resource": ""
} | |
q35403 | createFilter | train | function createFilter(filterExpression) {
if (typeof filterExpression === 'undefined') {
throw new Error('Filter expression should be defined');
}
if (isSimpleType(filterExpression)) {
return simpleTypeFilter(filterExpression);
} else if (isCustomPredicate(filterExpression)) {
return customPredicateFilter(filterExpression);
} else if (isArray(filterExpression)) {
return arrayFilter(filterExpression);
}
return customObjectFilter(filterExpression);
} | javascript | {
"resource": ""
} |
q35404 | toUnicode | train | function toUnicode(charCode) {
var result = charCode.toString(16).toUpperCase();
while (result.length < 4) result = '0' + result;
return '\\u' + result;
} | javascript | {
"resource": ""
} |
q35405 | PermissionError | train | function PermissionError(message, userName, actionKey) {
this.name = "PermissionError";
this.message = message || (userName && actionKey) ? "Permission Error. User " + userName + " is not authorized to " + actionKey : "Permission Error";
this.localizedMessageKey = "permission-error";
} | javascript | {
"resource": ""
} |
q35406 | create | train | function create(opt_options) {
function runInclude(file, encoding, callback) {
if (file.isNull()) {
return callback(null, file);
}
if (file.isStream()) {
this.emit('error', new PluginError(PLUGIN_NAME,
'Streams not supported!'));
}
if (file.isBuffer()) {
addIncludesToFile(file, opt_options).then((file) => {
return callback(null, file);
})
.catch(() => {
return callback(null, file);
});
}
}
var rv = function() {
return through.obj(runInclude);
};
return rv;
} | javascript | {
"resource": ""
} |
q35407 | addIncludesToFile | train | async function addIncludesToFile(file,
opt_options) {
const overrideMap = await readComponentsMap('./amp-versions.json');
const html = file.contents.toString();
const newHtml = await addIncludesToHtml(html, overrideMap, opt_options);
file.contents = new Buffer(newHtml);
return file;
} | javascript | {
"resource": ""
} |
q35408 | addIncludesToHtml | train | async function addIncludesToHtml(html, overrideMap,
opt_options) {
let instance = await amphtmlValidator.getInstance();
const options = opt_options || {};
if (options.updateComponentsMap) {
await updateComponentMap();
}
const versionMap = await readComponentsMap(COMPONENTS_MAP_PATH);
const result = instance.validateString(html);
const placeholder = options.placeholder || DEFAULT_AMP_PLACEHOLDER;
const mode = options.mode || DEFAULT_INSERTION_MODE;
// It is necessary to escape the placeholder as it is used in a RegExp object
// for example ${ampjs} -> \\$\\{ampjs\\}.
// Furthermore, the regular expression is defined to also match any
// preceding whitespace too, so that inserted tags can be indented to match.
const escapedPlaceholder = new RegExp('([^\\S\\r\\n]*)'
+ escapeRegex(placeholder));
var missingScriptUrls = new Set();
if (result.status === 'FAIL') {
// Determine whether the base AMP script element is missing.
for (err of result.errors) {
if (err.category === 'MANDATORY_AMP_TAG_MISSING_OR_INCORRECT'
&& err.code === 'MANDATORY_TAG_MISSING'
&& err.params && err.params[0] === 'amphtml engine v0.js script') {
missingScriptUrls.add(AMP_BASE_URL_ELEMENT);
break;
}
}
// Filter for only those errors indicating a missing script tag.
const tagErrors = result.errors
.filter(err => {
return err.category === 'MANDATORY_AMP_TAG_MISSING_OR_INCORRECT'
&& (err.code === 'MISSING_REQUIRED_EXTENSION'
|| err.code === 'ATTR_MISSING_REQUIRED_EXTENSION')});
for (let tagError of tagErrors) {
const tagName = tagError.params[1];
if (overrideMap[tagName]) {
var tagVersion = overrideMap[tagName];
} else if (options.forceLatest) {
var tagVersion = 'latest';
} else if (versionMap[tagName]) {
var tagVersion = versionMap[tagName];
}
if (!tagVersion) {
throw Error('Unknown AMP Component ' + tagName);
}
missingScriptUrls.add(createAmpCustomElementTag(tagName, tagVersion));
}
}
if (missingScriptUrls.size) {
if (mode === MODES.PLACEHOLDER) {
return addScriptUrlsByPlaceHolder(html, missingScriptUrls,
escapedPlaceholder);
} else {
return addScriptUrlsByHeaderInsertion(html, missingScriptUrls);
}
}
return html;
} | javascript | {
"resource": ""
} |
q35409 | updateComponentMap | train | async function updateComponentMap() {
const response = await fetch(GITHUB_AMPHTML_TREE_URL);
const data = await response.json();
const pairs = data.tree.map((item) => item.path.match(REGEX_EXTENSION_DIR))
.filter((match) => match && !match[1].endsWith('impl'))
.map((match) => [match[1], match[2]]);
const versionMap = {};
pairs.forEach((pair) => {
if (!versionMap[pair[0]] || versionMap[pair[0]] < pair[1]) {
versionMap[pair[0]] = pair[1];
}
});
writeComponentsMap(COMPONENTS_MAP_PATH, versionMap);
} | javascript | {
"resource": ""
} |
q35410 | writeComponentsMap | train | function writeComponentsMap(path, componentsMap) {
return new Promise((resolve, reject) => {
const data = JSON.stringify(componentsMap);
fs.writeFile(path, data, (err) => {
if (err) {
return reject(err);
}
resolve(data.length);
});
});
} | javascript | {
"resource": ""
} |
q35411 | readComponentsMap | train | async function readComponentsMap(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, (err, data) => {
if (err) {
return resolve({});
}
resolve(JSON.parse(data));
});
});
} | javascript | {
"resource": ""
} |
q35412 | createAmpCustomElementTag | train | function createAmpCustomElementTag(tagName, version) {
const scriptType = AMP_SCRIPT_TYPE_MAP[tagName] || 'custom-element';
return `<script async ${scriptType}="${tagName}" ` +
`src="https://cdn.ampproject.org/v0/${tagName}-${version}.js"></script>`;
} | javascript | {
"resource": ""
} |
q35413 | train | function( cssFileUrl )
{
if ( this.$.createStyleSheet )
this.$.createStyleSheet( cssFileUrl );
else
{
var link = new CKEDITOR.dom.element( 'link' );
link.setAttributes(
{
rel :'stylesheet',
type : 'text/css',
href : cssFileUrl
});
this.getHead().append( link );
}
} | javascript | {
"resource": ""
} | |
q35414 | train | function()
{
var head = this.$.getElementsByTagName( 'head' )[0];
if ( !head )
head = this.getDocumentElement().append( new CKEDITOR.dom.element( 'head' ), true );
else
head = new CKEDITOR.dom.element( head );
return (
this.getHead = function()
{
return head;
})();
} | javascript | {
"resource": ""
} | |
q35415 | isActionsExistsInPermissionActions | train | function isActionsExistsInPermissionActions(allActions, schemaActions) {
return utils.contains(allActions.sort().join(), schemaActions.sort().join());
} | javascript | {
"resource": ""
} |
q35416 | insertSettingsPluginsPermission | train | function insertSettingsPluginsPermission(app, next) {
var pluginsHome = utils.getRootPath() + "/plugins",
settingsPlugins = Object.keys(plugins.getSettingsPlugins());
var dbActionInstance = DBActions.getSimpleInstance(app, "SchemaPermissions");
var pluginInstanceHandler = require(utils.getLibPath() + "/PluginInstanceHandler"),
Roles = require(utils.getLibPath() + "/permissions/Roles"),
guestRoleId = Roles.getGuestRole().roleId,
userRoleId = Roles.getUserRole().roleId;
var mapFunction = function (pluginId, next) {
var permissions = pluginInstanceHandler.Permissions;
var model = {
actionsValue: permissions.actionsValue,
permissionSchemaKey: utils.getSettingsPluginPermissionSchemaKey(pluginId)
};
var rolePermissions = _.clone(permissions.rolePermissions);
//guest has nothing to do with settings plugin as its a non logged in user
delete rolePermissions[guestRoleId];
//user role only have permission to show user manage plugin, to modify his profile
if(pluginId != "userManage"){
rolePermissions[userRoleId] = [];
}
model.rolePermissions = rolePermissions;
Cache.store(model);
dbActionInstance.save(model, next);
};
async.eachSeries(settingsPlugins, mapFunction, function (err, results) {
next(err, true);
});
} | javascript | {
"resource": ""
} |
q35417 | train | function()
{
this.fire( 'beforeGetData' );
var eventData = this._.data;
if ( typeof eventData != 'string' )
{
var element = this.element;
if ( element && this.elementMode == CKEDITOR.ELEMENT_MODE_REPLACE )
eventData = element.is( 'textarea' ) ? element.getValue() : element.getHtml();
else
eventData = '';
}
eventData = { dataValue : eventData };
// Fire "getData" so data manipulation may happen.
this.fire( 'getData', eventData );
return eventData.dataValue;
} | javascript | {
"resource": ""
} | |
q35418 | train | function( writer, filter )
{
var comment = this.value;
if ( filter )
{
if ( !( comment = filter.onComment( comment, this ) ) )
return;
if ( typeof comment != 'string' )
{
comment.parent = this.parent;
comment.writeHtml( writer, filter );
return;
}
}
writer.comment( comment );
} | javascript | {
"resource": ""
} | |
q35419 | RetryPolicy | train | function RetryPolicy(options) {
options = options || {};
if (typeof options.maxAttempts === 'number') {
this.maxAttempts = options.maxAttempts;
}
else {
this.maxAttempts = RetryPolicy.DEFAULT_MAX_ATTEMPTS;
}
if (typeof options.codes === 'function') {
this.isRetryable = options.codes;
}
else {
this.codes = options.codes || RetryPolicy.DEFAULT_RETRYABLE_ERRORS;
}
} | javascript | {
"resource": ""
} |
q35420 | train | function(command, arg) {
if (!arg) {
arg = 'default';
}
if (!commands[command]) {
grunt.fail.fatal('Command [' + command + '] not found.');
}
// Check arg
if (typeof (commands[command]) !== 'function') {
if (!commands[command][arg]) {
grunt.fail.fatal('Argument [' + arg + '] for [' + command
+ '] not found.');
}
}
var func = (arg) ? commands[command][arg] : commands[command];
if (!func) {
func = commands[command]; // fallback to the main function
}
var options = this.options();
var docker = (options.docker) ? new Docker(options.docker) : null;
var done = this.async();
var callback = function(e) {
if (e) {
grunt.fail.warn(e);
}
done();
};
func.apply(this, [ grunt, docker, options, callback, arg ]);
} | javascript | {
"resource": ""
} | |
q35421 | _calculateDerivative | train | function _calculateDerivative(out, state, job, t, dt, d) {
vec3.scaleAndAdd(state.position, state.position, d.velocity, dt);
vec3.scaleAndAdd(state.momentum, state.momentum, d.force, dt);
_geometry.scaleAndAddQuat(state.orientation, state.orientation, d.spin, dt);
vec3.scaleAndAdd(state.angularMomentum, state.angularMomentum, d.torque, dt);
state.updateDependentFields();
out.velocity = state.velocity;
out.spin = state.spin;
vec3.set(out.force, 0, 0, 0);
vec3.set(out.torque, 0, 0, 0);
_forceApplierOutput.force = out.force;
_forceApplierOutput.torque = out.torque;
_forceApplierInput.state = state;
_forceApplierInput.t = t + dt;
_forceApplierInput.dt = dt;
job.applyForces(_forceApplierOutput, _forceApplierInput);
} | javascript | {
"resource": ""
} |
q35422 | Cache | train | function Cache(maxSize, debug, storage) {
this.maxSize_ = maxSize || -1;
this.debug_ = debug || false;
this.storage_ = storage || new Cache.BasicCacheStorage();
this.fillFactor_ = .75;
this.stats_ = {};
this.stats_['hits'] = 0;
this.stats_['misses'] = 0;
this.log_('Initialized cache with size ' + maxSize);
} | javascript | {
"resource": ""
} |
q35423 | Prompt | train | function Prompt() {
BasePrompt.apply(this, arguments);
if (typeof this.question.source !== 'function') {
throw new TypeError('expected source to be defined');
}
this.currentChoices = [];
this.firstRender = true;
this.selected = 0;
// Make sure no default is set (so it won't be printed)
this.question.default = undefined;
this.paginator = new Paginator();
} | javascript | {
"resource": ""
} |
q35424 | insertCallback | train | function insertCallback(error, data) {
console.log(require('util').inspect(error ? error.message : data, { showHidden: true, colors: true, depth: 2 }));
} | javascript | {
"resource": ""
} |
q35425 | train | function(tag, confImage, callback) {
grunt.log.subhead(actioning[action] + ' image [' + tag + ']');
async.waterfall([
// Step 1: search for a running container with the same image
function(cb) {
docker.listContainers({
all : 1,
// filters: (action !== 'unpause') ? '{"status":["running"]}' : null
}, function(err, containers) {
if (err) {
return cb(err);
}
var container = null;
for (var c = 0; c < containers.length; c++) {
if (containers[c].Image.indexOf(utils.qualifiedImageName(tag,
options.registry, null)) === 0) {
container = containers[c];
break;
}
}
cb(null, container);
});
},
// Step 2: stop it
function(container, cb) {
if (container) {
grunt.log.writeln("Found a matched container, " + action + " it.");
var dockcontainer = docker.getContainer(container.Id);
var opts = confImage.options && confImage.options[action] || {};
dockcontainer[action](opts, function(e, stream) {
if (stream && stream.readable) {
stream.setEncoding('utf8');
stream.on('error', cb);
stream.on('end', cb);
stream.on('data', grunt.log.write);
} else {
cb(e);
}
});
} else {
grunt.log.writeln("No matched container with this image.");
cb(null);
}
}, ], callback);
} | javascript | {
"resource": ""
} | |
q35426 | PluginRender | train | function PluginRender(pluginInstance, rendererInstance) {
this._view = "index.jade";
this._locals = {};
var ns = pluginInstance.pluginNamespace, obj = PluginHelper.getPluginIdAndIId(ns), pluginId = obj.pluginId,
req = PluginHelper.cloneRequest(rendererInstance.req, pluginId), res = rendererInstance.res;
Object.defineProperties(req.params, {
plugin: {
value: obj.pluginId
},
iId: {
value: obj.iId
},
namespace: {
value: ns
}
});
Object.defineProperties(req, {
pluginRender: {
value: this
}
});
Object.defineProperties(this, {
req: {
value: req
},
res: {
value: res
},
pluginId: {
value: req.params.plugin
},
iId: {
value: req.params.iId
},
plugin: {
value: Plugins.get(req.params.plugin)
},
namespace: {
value: req.params.namespace
},
pluginInstance: {
value: pluginInstance
},
theme: {
value: rendererInstance.theme
},
page: {
value: rendererInstance.page
},
pluginPermissionValidator: {
value: rendererInstance.pluginPermissionValidator
},
pagePermissionValidator: {
value: rendererInstance.pagePermissionValidator
},
pluginInstanceDBAction: {
value: rendererInstance.pluginInstanceDBAction
},
isExclusive: {
value: rendererInstance.isExclusive
}
});
} | javascript | {
"resource": ""
} |
q35427 | filter | train | function filter(socket, message, rinfo) {
const isAllowedAddress = socket.remoteAddress === rinfo.address;
const isAllowedPort = socket.remotePort === rinfo.port;
return isAllowedAddress && isAllowedPort;
} | javascript | {
"resource": ""
} |
q35428 | propsStream | train | function propsStream(options) {
if (!_.isObject(options)) {
options = {};
}
return through.obj(function(chunk, enc, cb) {
var webpackOptions = chunk[FIELD_NAME] || {};
webpackOptions = _.merge(webpackOptions, options);
chunk[FIELD_NAME] = webpackOptions;
cb(null, chunk);
});
} | javascript | {
"resource": ""
} |
q35429 | train | function (logger, key, options) {
return new Promise((resolve, reject) => {
var url = `http://${options.host}:${options.port}/v1/kv/${key}`;
logger.trace(`GET ${url}`);
request.get(url)
.timeout(options.timeout)
.then((res) => {
logger.trace(`GET ${url} - 200`);
resolve(res.body);
})
.catch((error) => {
logger.trace(`GET ${url} - ${error.status}`);
if (error.status === 404) {
return resolve(null);
}
var code = ConfigError.CODES.UNKNOWN_ERROR;
if (error.code === 'ECONNREFUSED') {
code = ConfigError.CODES.CONSUL_ECONNREFUSED;
} else if (
error.code === 'ECONNABORTED' &&
typeof error.timeout === 'number'
) {
code = ConfigError.CODES.CONSUL_TIMEOUT;
}
var exception = ConfigError.createError(code, error);
exception.bind({method: 'GET', url: url});
reject(exception);
});
});
} | javascript | {
"resource": ""
} | |
q35430 | train | function()
{
var heightType = this.getDialog().getContentElement( 'info', 'htmlHeightType' ),
labelElement = heightType.getElement(),
inputElement = this.getInputElement(),
ariaLabelledByAttr = inputElement.getAttribute( 'aria-labelledby' );
inputElement.setAttribute( 'aria-labelledby', [ ariaLabelledByAttr, labelElement.$.id ].join( ' ' ) );
} | javascript | {
"resource": ""
} | |
q35431 | createGraphIterators | train | function createGraphIterators(graph) {
return {
/**
* Creates a vertex iterator stream. This is an entry point for all traversal
* starting with a node.
*
* @param {string|number} [startFrom] vertex id to start iteration from.
* If this argument is omitted, then all graph nodes are iterated
*
* @returns {VertexPipe}
*/
V: function createVertexStream(startFrom) {
var VertexPipe = require('./lib/pipes/vertexPipe');
var VertexIterator = require('./lib/iterators/vertexIterator');
var vertexPipe = new VertexPipe(graph);
vertexPipe.setSourcePipe(new VertexIterator(graph, startFrom));
return vertexPipe;
}
};
} | javascript | {
"resource": ""
} |
q35432 | normalizeRoute | train | function normalizeRoute(path, parent) {
if (path[0] === '/' || path[0] === '') {
return path; // absolute route
}
if (!parent) {
return path; // no need for a join
}
return `${parent.route}/${path}`; // join
} | javascript | {
"resource": ""
} |
q35433 | plugin | train | function plugin() {
return function(files, metalsmith, done) {
Object.keys(files).forEach(function(file) {
if (!~file.indexOf('.html')) return;
var $ = cheerio.load(files[file].contents);
var links = $('a');
for (var i = links.length - 1; i >= 0; i--) {
var url = links[i].attribs.href;
if (image(url)) $(links[i]).append(img(url));
}
$.root().prepend(css());
files[file].contents = new Buffer($.html());
});
done();
};
} | javascript | {
"resource": ""
} |
q35434 | image | train | function image(filename) {
if (!filename) return;
var ext = filename.split('.')[filename.split('.').length - 1];
return ~extensions.join().indexOf(ext);
} | javascript | {
"resource": ""
} |
q35435 | callItems | train | function callItems( currentEntry )
{
var isNode = currentEntry.type
|| currentEntry instanceof CKEDITOR.htmlParser.fragment;
for ( var i = 0 ; i < this.length ; i++ )
{
// Backup the node info before filtering.
if ( isNode )
{
var orgType = currentEntry.type,
orgName = currentEntry.name;
}
var item = this[ i ],
ret = item.apply( window, arguments );
if ( ret === false )
return ret;
// We're filtering node (element/fragment).
if ( isNode )
{
// No further filtering if it's not anymore
// fitable for the subsequent filters.
if ( ret && ( ret.name != orgName
|| ret.type != orgType ) )
{
return ret;
}
}
// Filtering value (nodeName/textValue/attrValue).
else
{
// No further filtering if it's not
// any more values.
if ( typeof ret != 'string' )
return ret;
}
ret != undefined && ( currentEntry = ret );
}
return currentEntry;
} | javascript | {
"resource": ""
} |
q35436 | train | function (dir, appname, version) {
if (appname) {
dir = path.join(dir, appname);
if (version) {
dir = path.join(dir, version);
}
}
return dir;
} | javascript | {
"resource": ""
} | |
q35437 | deletePage | train | function deletePage(req, res, next) {
var that = this, db = that.getDB(), DBActions = that.getDBActionsLib(),
dbAction = DBActions.getAuthInstance(req, PAGE_SCHEMA, PAGE_PERMISSION_SCHEMA_ENTRY);
var params = req.params;
var pageId = params.id;
if (!pageId) {
that.setErrorMessage(req, "No page is selected");
return next(null);
}
var redirect = req.params.page + "/" + req.params.plugin;
dbAction.get("findByPageId", pageId, function (err, page) {
if (err) {
return next(err);
}
page && (page = page.toObject());
if (page && (that.getAppProperty("DEFAULT_INDEX_PAGE") == page.friendlyURL)) {
that.setErrorMessage(req, "Cannot delete index page.");
that.setRedirect(req, redirect);
return next(null);
}
PageManager.hasChildren(dbAction, pageId, function (err, pages) {
if (pages.length > 0) {
that.setRedirect(req, redirect);
that.setErrorMessage(req, "Delete all child pages.");
next(err);
} else {
var aboveSiblings;
async.series([
function (n) {
dbAction.authorizedRemove(pageId, n);
},
function (n) {
PageManager.getAboveSiblings(dbAction, page, function (err, pages) {
if (pages) {
aboveSiblings = pages;
}
n(err, pages);
});
},
function (n) {
if (!aboveSiblings || aboveSiblings.length == 0) {
return n(null, true);
}
var dbAction1 = DBActions.getInstance(req, PAGE_SCHEMA);
var decrementPageOrder = function (page, n) {
var order = page.order;
--order;
dbAction1.update({
pageId: page.pageId,
order: order
}, n);
};
async.each(aboveSiblings, decrementPageOrder, n);
}
], function (err, result) {
if (!err) {
that.setRedirect(req, redirect);
that.setSuccessMessage(req, "Page deleted successfully.");
}
next(err);
});
}
});
})
} | javascript | {
"resource": ""
} |
q35438 | setupWatcher | train | function setupWatcher(app, dbAction, name) {
dbAction.get("findByName", name, function (err, theme) {
if (!err && theme) {
require(utils.getLibPath() + "/static/ThemesWatcher").cacheAndWatchTheme(app, theme);
}
});
} | javascript | {
"resource": ""
} |
q35439 | filterAndSortAvailableServers | train | function filterAndSortAvailableServers (serverArray) {
var copyOfServerArray = JSON.parse(JSON.stringify(serverArray));
copyOfServerArray.sort(function (itemOne, itemTwo) {
return sortValue(itemOne) - sortValue(itemTwo);
});
// Filter servers we've too-recently disconnected from
return copyOfServerArray.filter(haveNotDisconnectedFromRecently);
} | javascript | {
"resource": ""
} |
q35440 | ValidatedPath | train | function ValidatedPath(path, firstPathPart, pathRemainder) {
this.path = path;
this.firstPathPart = firstPathPart;
this.pathRemainder = pathRemainder;
} | javascript | {
"resource": ""
} |
q35441 | streamHandler | train | function streamHandler(stream) {
return stream
.pipe(plumber())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(sourcemaps.write('.', {includeContent: true, sourceRoot: '.'}))
.pipe(gulp.dest(dest));
} | javascript | {
"resource": ""
} |
q35442 | reducer | train | function reducer(context, action, target, state) {
const newState = Object.assign({}, state);
let actor;
switch(action.type) {
case INIT_CONTEXT_ACTION_TYPE:
newState.days = context.reduce((acc, actor, name) => {
if(name.indexOf("_weekDay") > 0)
acc.push(name);
return acc;
}, []);
return newState;
case "resetDays":
context.map(resetDays);
return newState;
case "deselectDays":
context.map(deselectDays);
return newState;
case "daySelected":
const selected = context.find(newState.selectedDay);
if(selected){
removeSelection(context, newState);
}
actor = context.find(target, {pushClassNames: raiseTargetNotfound(target)});
actor.pushClassNames(".calendar.day_label-selected");
newState.selectedDay = target;
return newState;
case "clearSelectedDay":
removeSelection(context, newState);
return newState;
case "changeMonth":
removeSelection(context, newState);
return newState;
case "changeCalendar":
context.map(function(actor){
if(!actor || actor.name === undefined)
raiseTargetNotfound(target);
const className = actor.getInitialClassName();
actor.resetClassNames([className,
className+"-lang_"+action.lang,
"#"+actor.name,
"#"+actor.name+"-lang_"+action.lang,
"#"+actor.name+"-os_"+System.OS
]);
// actor.pushClassName("#"+actor.name+"-os_"+System.OS);
});
return newState;
case "updateDayType":
actor = context.find(target);
const data = action.data;
if(data.isWeekend) {
actor.pushClassNames(".calendar.day_label-weekend");
}
if(Array.isArray(data.specialDay) && data.specialDay.length > 0) {
actor.pushClassNames(".calendar.day_label-specialDay");
}
if(data.month != "current") {
actor.pushClassNames(".calendar.day_label-deactiveDays");
}
return newState;
}
return state;
} | javascript | {
"resource": ""
} |
q35443 | emitBuffer | train | function emitBuffer() {
if (!this._buffer) {
return;
}
for (var i = this._marker; i < this._buffer.length; i++) {
var data = this._buffer[i];
if (data.writable === true) {
break;
} else if (data.writable === false) {
emitBuffer.call(data);
} else {
this.emit('data', data, 'utf8');
}
}
if (i === this._buffer.length) {
delete this._buffer;
delete this._marker;
if (!this.writable) {
this.emit('end');
}
} else {
this._marker = i;
}
} | javascript | {
"resource": ""
} |
q35444 | setOptions | train | function setOptions( options ){
if( this.addListener ){
for( var opt in options ){
if( typeof( options[ opt ] ) !== 'function' || !(/^on[A-z]/).test(opt)){
continue;
}
this.addListener( removeOn( opt ), options[ opt ]);
delete options[opt];
}
}
this.options = merge.apply(null, append([{}, this.options], arguments ) );
return this;
} | javascript | {
"resource": ""
} |
q35445 | sanitize | train | function sanitize(htmlText, opt_uriPolicy, opt_nmTokenPolicy) {
var out = [];
makeHtmlSanitizer(
function sanitizeAttribs(tagName, attribs) {
for (var i = 0; i < attribs.length; i += 2) {
var attribName = attribs[i];
var value = attribs[i + 1];
var atype = null, attribKey;
if ((attribKey = tagName + '::' + attribName,
html4.ATTRIBS.hasOwnProperty(attribKey))
|| (attribKey = '*::' + attribName,
html4.ATTRIBS.hasOwnProperty(attribKey))) {
atype = html4.ATTRIBS[attribKey];
}
if (atype !== null) {
switch (atype) {
case html4.atype.NONE: break;
case html4.atype.SCRIPT:
case html4.atype.STYLE:
value = null;
break;
case html4.atype.ID:
case html4.atype.IDREF:
case html4.atype.IDREFS:
case html4.atype.GLOBAL_NAME:
case html4.atype.LOCAL_NAME:
case html4.atype.CLASSES:
value = opt_nmTokenPolicy ? opt_nmTokenPolicy(value) : value;
break;
case html4.atype.URI:
var parsedUri = ('' + value).match(URI_SCHEME_RE);
if (!parsedUri) {
value = null;
} else if (!parsedUri[1] ||
WHITELISTED_SCHEMES.test(parsedUri[1])) {
value = opt_uriPolicy && opt_uriPolicy(value);
} else {
value = null;
}
break;
case html4.atype.URI_FRAGMENT:
if (value && '#' === value.charAt(0)) {
value = opt_nmTokenPolicy ? opt_nmTokenPolicy(value) : value;
if (value) { value = '#' + value; }
} else {
value = null;
}
break;
default:
value = null;
break;
}
} else {
value = null;
}
attribs[i + 1] = value;
}
return attribs;
})(htmlText, out);
return out.join('');
} | javascript | {
"resource": ""
} |
q35446 | onDown | train | function onDown(e) {
// Prevent interaction offset calculations happening while
// the user is dragging the map.
//
// Store this event so that we can compare it to the
// up event
_downLock = true;
var _e = (e.type !== "MSPointerDown" && e.type !== "pointerdown" ? e : e.originalEvent);
_d = wax.u.eventoffset(_e);
if (e.type === 'mousedown') {
bean.add(document.body, 'click', onUp);
// track mouse up to remove lockDown when the drags end
bean.add(document.body, 'mouseup', dragEnd);
// Only track single-touches. Double-touches will not affect this
// control
} else if (e.type === 'touchstart' && e.touches.length === 1) {
//GMaps fix: Because it's triggering always mousedown and click, we've to remove it
bean.remove(document.body, 'click', onUp); //GMaps fix
//When we finish dragging, then the click will be
bean.add(document.body, 'click', onUp);
bean.add(document.body, 'touchEnd', dragEnd);
} else if (e.originalEvent.type === "MSPointerDown" && e.originalEvent.touches && e.originalEvent.touches.length === 1) {
// Don't make the user click close if they hit another tooltip
bean.fire(interaction, 'off');
// Touch moves invalidate touches
bean.add(parent(), mspointerEnds);
} else if (e.type === "pointerdown" && e.originalEvent.touches && e.originalEvent.touches.length === 1) {
// Don't make the user click close if they hit another tooltip
bean.fire(interaction, 'off');
// Touch moves invalidate touches
bean.add(parent(), pointerEnds);
} else {
// Fix layer interaction in IE10/11 (CDBjs #139)
// Reason: Internet Explorer is triggering pointerdown when you click on the marker, and other browsers don't.
// Because of that, _downLock was active and it believed that you're dragging the map, instead of dragging the marker
_downLock = false;
}
} | javascript | {
"resource": ""
} |
q35447 | initTouch | train | function initTouch()
{
var startX,
startY,
touchStartX,
touchStartY,
moved,
moving = false;
container.unbind('touchstart.jsp touchmove.jsp touchend.jsp click.jsp-touchclick').bind(
'touchstart.jsp',
function(e)
{
var touch = e.originalEvent.touches[0];
startX = contentPositionX();
startY = contentPositionY();
touchStartX = touch.pageX;
touchStartY = touch.pageY;
moved = false;
moving = true;
}
).bind(
'touchmove.jsp',
function(ev)
{
if(!moving) {
return;
}
var touchPos = ev.originalEvent.touches[0],
dX = horizontalDragPosition, dY = verticalDragPosition;
jsp.scrollTo(startX + touchStartX - touchPos.pageX, startY + touchStartY - touchPos.pageY);
moved = moved || Math.abs(touchStartX - touchPos.pageX) > 5 || Math.abs(touchStartY - touchPos.pageY) > 5;
// return true if there was no movement so rest of screen can scroll
return dX == horizontalDragPosition && dY == verticalDragPosition;
}
).bind(
'touchend.jsp',
function(e)
{
moving = false;
/*if(moved) {
return false;
}*/
}
).bind(
'click.jsp-touchclick',
function(e)
{
if(moved) {
moved = false;
return false;
}
}
);
} | javascript | {
"resource": ""
} |
q35448 | train | function(vars) {
var c = this.compiled = this.compiled || this.get('compiled') || this.compile();
var rendered = c(vars);
return rendered;
} | javascript | {
"resource": ""
} | |
q35449 | train | function(args) {
var self = this;
// var date = new Date();
this.trigger('loadModelStarted');
$.when(this.elder('fetch', args)).done(function(ev){
self.trigger('loadModelCompleted', ev);
// var dateComplete = new Date()
// console.log('completed in '+(dateComplete - date));
}).fail(function(ev) {
self.trigger('loadModelFailed', ev);
})
} | javascript | {
"resource": ""
} | |
q35450 | train | function(ev, obj, retrigEvent) {
if(!retrigEvent) {
retrigEvent = ev;
}
var self = this;
obj.bind && obj.bind(ev, function() {
self.trigger(retrigEvent);
}, self)
} | javascript | {
"resource": ""
} | |
q35451 | train | function() {
var self = this;
this.trigger('clean');
this.clearSubViews();
// remove from parent
if(this._parent) {
this._parent.removeView(this);
this._parent = null;
}
this.remove();
this.unbind();
// remove this model binding
if (this.model && this.model.unbind) this.model.unbind(null, null, this);
// remove model binding
_(this._models).each(function(m) {
m.unbind(null, null, self);
});
this._models = [];
View.viewCount--;
delete View.views[this.cid];
return this;
} | javascript | {
"resource": ""
} | |
q35452 | train | function(ev) {
if(ev && ev.preventDefault) {
ev.preventDefault();
};
if(ev && ev.stopPropagation) {
ev.stopPropagation();
};
} | javascript | {
"resource": ""
} | |
q35453 | train | function() {
_.each(cdb.core.View.views, function(view) {
_.each(view, function(prop, k) {
if( k !== '_parent' &&
view.hasOwnProperty(k) &&
prop instanceof cdb.core.View &&
view._subviews[prop.cid] === undefined) {
console.log("=========");
console.log("untracked view: ");
console.log(prop.el);
console.log('parent');
console.log(view.el);
console.log(" ");
}
});
});
} | javascript | {
"resource": ""
} | |
q35454 | train | function() {
var e = this.get('extra_params') || e;
e.cache_buster = new Date().getTime();
this.set('extra_params', e);
this.trigger('change', this);
} | javascript | {
"resource": ""
} | |
q35455 | train | function(model, col, options) {
if (this.size() > 0) {
// Assign an order of 0 to the first layer
this.at(0).set({ order: 0 });
if (this.size() > 1) {
var layersByType = {};
for (var i = 1; i < this.size(); ++i) {
var layer = this.at(i);
var layerType = layer.get('type');
layersByType[layerType] = layersByType[layerType] || [];
layersByType[layerType].push(layer);
}
var lastOrder = 0;
var sortedTypes = [CARTODB_LAYER_TYPE, TORQUE_LAYER_TYPE, TILED_LAYER_TYPE];
for (var i = 0; i < sortedTypes.length; ++i) {
var type = sortedTypes[i];
var layers = layersByType[type] || [];
for (var j = 0; j < layers.length; ++j) {
var layer = layers[j];
layer.set({
order: ++lastOrder
});
}
}
}
}
} | javascript | {
"resource": ""
} | |
q35456 | train | function(options) {
if (typeof options != "object" || options.length) {
if (this.options.debug) {
throw (options + ' options has to be an object');
} else {
return;
}
}
// Set options
_.defaults(this.options, options);
} | javascript | {
"resource": ""
} | |
q35457 | train | function(bounds, mapSize) {
var z = this.getBoundsZoom(bounds, mapSize);
if(z === null) {
return;
}
// project -> calculate center -> unproject
var swPoint = cdb.geo.Map.latlngToMercator(bounds[0], z);
var nePoint = cdb.geo.Map.latlngToMercator(bounds[1], z);
var center = cdb.geo.Map.mercatorToLatLng({
x: (swPoint[0] + nePoint[0])*0.5,
y: (swPoint[1] + nePoint[1])*0.5
}, z);
this.set({
center: center,
zoom: z
})
} | javascript | {
"resource": ""
} | |
q35458 | train | function(boundsSWNE, mapSize) {
// sometimes the map reports size = 0 so return null
if(mapSize.x === 0 || mapSize.y === 0) return null;
var size = [mapSize.x, mapSize.y],
zoom = this.get('minZoom') || 0,
maxZoom = this.get('maxZoom') || 24,
ne = boundsSWNE[1],
sw = boundsSWNE[0],
boundsSize = [],
nePoint,
swPoint,
zoomNotFound = true;
do {
zoom++;
nePoint = cdb.geo.Map.latlngToMercator(ne, zoom);
swPoint = cdb.geo.Map.latlngToMercator(sw, zoom);
boundsSize[0] = Math.abs(nePoint[0] - swPoint[0]);
boundsSize[1] = Math.abs(swPoint[1] - nePoint[1]);
zoomNotFound = boundsSize[0] <= size[0] || boundsSize[1] <= size[1];
} while (zoomNotFound && zoom <= maxZoom);
if (zoomNotFound) {
return maxZoom;
}
return zoom - 1;
} | javascript | {
"resource": ""
} | |
q35459 | train | function() {
var result = [];
for (var s in this._subviews) {
if(this._subviews[s] instanceof cdb.geo.ui.Infowindow) {
result.push(this._subviews[s]);
}
}
return result;
} | javascript | {
"resource": ""
} | |
q35460 | train | function() {
this._unbindModel();
this.map.bind('change:view_bounds_sw', this._changeBounds, this);
this.map.bind('change:view_bounds_ne', this._changeBounds, this);
this.map.bind('change:zoom', this._setZoom, this);
this.map.bind('change:scrollwheel', this._setScrollWheel, this);
this.map.bind('change:keyboard', this._setKeyboard, this);
this.map.bind('change:center', this._setCenter, this);
this.map.bind('change:attribution', this.setAttribution, this);
} | javascript | {
"resource": ""
} | |
q35461 | train | function() {
this.map.unbind('change:view_bounds_sw', null, this);
this.map.unbind('change:view_bounds_ne', null, this);
this.map.unbind('change:zoom', null, this);
this.map.unbind('change:scrollwheel', null, this);
this.map.unbind('change:keyboard', null, this);
this.map.unbind('change:center', null, this);
this.map.unbind('change:attribution', null, this);
} | javascript | {
"resource": ""
} | |
q35462 | train | function(attributes) {
var fields = this.get('fields');
this.set('content', cdb.geo.ui.InfowindowModel.contentForFields(attributes, fields));
} | javascript | {
"resource": ""
} | |
q35463 | train | function() {
if(this.template) {
// If there is content, destroy the jscrollpane first, then remove the content.
var $jscrollpane = this.$(".cartodb-popup-content");
if ($jscrollpane.length > 0 && $jscrollpane.data() != null) {
$jscrollpane.data().jsp && $jscrollpane.data().jsp.destroy();
}
// Clone fields and template name
var fields = _.map(this.model.attributes.content.fields, function(field){
return _.clone(field);
});
var data = this.model.get('content') ? this.model.get('content').data : {};
// If a custom template is not applied, let's sanitized
// fields for the template rendering
if (this.model.get('template_name')) {
var template_name = _.clone(this.model.attributes.template_name);
// Sanitized them
fields = this._fieldsToString(fields, template_name);
}
// Join plan fields values with content to work with
// custom infowindows and CartoDB infowindows.
var values = {};
_.each(this.model.get('content').fields, function(pair) {
values[pair.title] = pair.value;
})
var obj = _.extend({
content: {
fields: fields,
data: data
}
},values);
this.$el.html(
cdb.core.sanitize.html(this.template(obj), this.model.get('sanitizeTemplate'))
);
// Set width and max-height from the model only
// If there is no width set, we don't force our infowindow
if (this.model.get('width')) {
this.$('.cartodb-popup').css('width', this.model.get('width') + 'px');
}
this.$('.cartodb-popup .cartodb-popup-content').css('max-height', this.model.get('maxHeight') + 'px');
// Hello jscrollpane hacks!
// It needs some time to initialize, if not it doesn't render properly the fields
// Check the height of the content + the header if exists
var self = this;
setTimeout(function() {
var actual_height = self.$(".cartodb-popup-content").outerHeight();
if (self.model.get('maxHeight') <= actual_height)
self.$(".cartodb-popup-content").jScrollPane({
verticalDragMinHeight: 20,
autoReinitialise: true
});
}, 1);
// If the infowindow is loading, show spin
this._checkLoading();
// If the template is 'cover-enabled', load the cover
this._loadCover();
if(!this.isLoadingData()) {
this.model.trigger('domready', this, this.$el);
this.trigger('domready', this, this.$el);
}
}
return this;
} | javascript | {
"resource": ""
} | |
q35464 | train | function() {
var template = this.model.get('template') ?
this.model.get('template') :
cdb.templates.getTemplate(this._getModelTemplate());
if(typeof(template) !== 'function') {
this.template = new cdb.core.Template({
template: template,
type: this.model.get('template_type') || 'mustache'
}).asFunction()
} else {
this.template = template
}
this.render();
} | javascript | {
"resource": ""
} | |
q35465 | train | function(ev) {
// If the mouse down come from jspVerticalBar
// dont stop the propagation, but if the event
// is a touchstart, stop the propagation
var come_from_scroll = (($(ev.target).closest(".jspVerticalBar").length > 0) && (ev.type != "touchstart"));
if (!come_from_scroll) {
ev.stopPropagation();
}
} | javascript | {
"resource": ""
} | |
q35466 | train | function(fields, template_name) {
var fields_sanitized = [];
if (fields && fields.length > 0) {
var self = this;
fields_sanitized = _.map(fields, function(field,i) {
// Return whole attribute sanitized
return self._sanitizeField(field, template_name, field.index || i);
});
}
return fields_sanitized;
} | javascript | {
"resource": ""
} | |
q35467 | train | function($el) {
this._stopSpinner();
var $el = this.$el.find('.loading');
if ($el) {
// Check if it is dark or other to change color
var template_dark = this.model.get('template_name').search('dark') != -1;
if (template_dark) {
this.spin_options.color = '#FFF';
} else {
this.spin_options.color = 'rgba(0,0,0,0.5)';
}
this.spinner = new Spinner(this.spin_options).spin();
$el.append(this.spinner.el);
}
} | javascript | {
"resource": ""
} | |
q35468 | train | function() {
var content = this.model.get("content");
if (content && content.fields && content.fields.length > 0) {
return (content.fields[0].value || '').toString();
}
return false;
} | javascript | {
"resource": ""
} | |
q35469 | train | function() {
if (!this._containsCover()) return;
var self = this;
var $cover = this.$(".cover");
var $img = $cover.find("img");
var $shadow = this.$(".shadow");
var url = this._getCoverURL();
if (!this._isValidURL(url)) {
$img.hide();
$shadow.hide();
cdb.log.info("Header image url not valid");
return;
}
// configure spinner
var target = document.getElementById('spinner');
var opts = { lines: 9, length: 4, width: 2, radius: 4, corners: 1, rotate: 0, color: '#ccc', speed: 1, trail: 60, shadow: true, hwaccel: false, zIndex: 2e9 };
var spinner = new Spinner(opts).spin(target);
// create the image
$img.hide(function() {
this.remove();
});
$img = $("<img />").attr("src", url);
$cover.append($img);
$img.load(function(){
spinner.stop();
var w = $img.width();
var h = $img.height();
var coverWidth = $cover.width();
var coverHeight = $cover.height();
var ratio = h / w;
var coverRatio = coverHeight / coverWidth;
// Resize rules
if ( w > coverWidth && h > coverHeight) { // bigger image
if ( ratio < coverRatio ) $img.css({ height: coverHeight });
else {
var calculatedHeight = h / (w / coverWidth);
$img.css({ width: coverWidth, top: "50%", position: "absolute", "margin-top": -1*parseInt(calculatedHeight, 10)/2 });
}
} else {
var calculatedHeight = h / (w / coverWidth);
$img.css({ width: coverWidth, top: "50%", position: "absolute", "margin-top": -1*parseInt(calculatedHeight, 10)/2 });
}
$img.fadeIn(300);
})
.error(function(){
spinner.stop();
});
} | javascript | {
"resource": ""
} | |
q35470 | train | function(url) {
if (url) {
var urlPattern = /^(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-|]*[\w@?^=%&\/~+#-])?$/
return String(url).match(urlPattern) != null ? true : false;
}
return false;
} | javascript | {
"resource": ""
} | |
q35471 | train | function() {
this.model.set({
content: {
fields: [{
title: null,
alternative_name: null,
value: 'Loading content...',
index: null,
type: "loading"
}],
data: {}
}
})
return this;
} | javascript | {
"resource": ""
} | |
q35472 | train | function(delay) {
if (!cdb.core.util.ie || (cdb.core.util.browser.ie && cdb.core.util.browser.ie.version > 8)) {
this.$el.css({
'marginBottom':'-10px',
'display': 'block',
'visibility':'visible',
opacity:0
});
this.$el
.delay(delay)
.animate({
opacity: 1,
marginBottom: 0
},300);
} else {
this.$el.show();
}
} | javascript | {
"resource": ""
} | |
q35473 | train | function() {
if (!$.browser.msie || ($.browser.msie && parseInt($.browser.version) > 8 )) {
var self = this;
this.$el.animate({
marginBottom: "-10px",
opacity: "0",
display: "block"
}, 180, function() {
self.$el.css({visibility: "hidden"});
});
} else {
this.$el.hide();
}
} | javascript | {
"resource": ""
} | |
q35474 | train | function () {
var offset = this.model.get("offset");
if (!this.model.get("autoPan") || this.isHidden()) { return; }
var
x = this.$el.position().left,
y = this.$el.position().top,
containerHeight = this.$el.outerHeight(true) + 15, // Adding some more space
containerWidth = this.$el.width(),
pos = this.mapView.latLonToPixel(this.model.get("latlng")),
adjustOffset = {x: 0, y: 0};
size = this.mapView.getSize()
wait_callback = 0;
if (pos.x - offset[0] < 0) {
adjustOffset.x = pos.x - offset[0] - 10;
}
if (pos.x - offset[0] + containerWidth > size.x) {
adjustOffset.x = pos.x + containerWidth - size.x - offset[0] + 10;
}
if (pos.y - containerHeight < 0) {
adjustOffset.y = pos.y - containerHeight - 10;
}
if (pos.y - containerHeight > size.y) {
adjustOffset.y = pos.y + containerHeight - size.y;
}
if (adjustOffset.x || adjustOffset.y) {
this.mapView.panBy(adjustOffset);
wait_callback = 300;
}
return wait_callback;
} | javascript | {
"resource": ""
} | |
q35475 | train | function(pos) {
var props = {};
if(pos.indexOf('top') !== -1) {
props.top = this.options.pos_margin;
} else if(pos.indexOf('bottom') !== -1) {
props.bottom = this.options.pos_margin;
}
if(pos.indexOf('left') !== -1) {
props.left = this.options.pos_margin;
} else if(pos.indexOf('right') !== -1) {
props.right = this.options.pos_margin;
}
this.$el.css(props);
} | javascript | {
"resource": ""
} | |
q35476 | train | function(payload) {
var self = this;
if (this.options.compressor) {
return this.options.compressor;
}
payload = payload || JSON.stringify(this.toJSON());
if (!this.options.force_compress && payload.length < this.options.MAX_GET_SIZE) {
return function(data, level, callback) {
callback("config=" + encodeURIComponent(data));
};
}
return function(data, level, callback) {
data = JSON.stringify({ config: data });
LZMA.compress(data, level, function(encoded) {
callback("lzma=" + encodeURIComponent(cdb.core.util.array2hex(encoded)));
});
};
} | javascript | {
"resource": ""
} | |
q35477 | train | function(params, included) {
if(!params) return '';
var url_params = [];
included = included || _.keys(params);
for(var i in included) {
var k = included[i]
var p = params[k];
if(p) {
if (_.isArray(p)) {
for (var j = 0, len = p.length; j < len; j++) {
url_params.push(k + "[]=" + encodeURIComponent(p[j]));
}
} else {
var q = encodeURIComponent(p);
q = q.replace(/%7Bx%7D/g,"{x}").replace(/%7By%7D/g,"{y}").replace(/%7Bz%7D/g,"{z}");
url_params.push(k + "=" + q);
}
}
}
return url_params.join('&')
} | javascript | {
"resource": ""
} | |
q35478 | train | function(layer, callback) {
layer = layer == undefined ? 0: layer;
var self = this;
this.getTiles(function(urls) {
if(!urls) {
callback(null);
return;
}
if(callback) {
callback(self._tileJSONfromTiles(layer, urls));
}
});
} | javascript | {
"resource": ""
} | |
q35479 | train | function(number) {
var layers = {}
var c = 0;
for(var i = 0; i < this.layers.length; ++i) {
var layer = this.layers[i];
layers[i] = c;
if(layer.options && !layer.options.hidden) {
++c;
}
}
return layers[number];
} | javascript | {
"resource": ""
} | |
q35480 | train | function(index) {
var layers = [];
for(var i = 0; i < this.layers.length; ++i) {
var layer = this.layers[i];
if(this._isLayerVisible(layer)) {
layers.push(i);
}
}
if (index >= layers.length) {
return -1;
}
return +layers[index];
} | javascript | {
"resource": ""
} | |
q35481 | train | function(layer, attributes) {
if(attributes === undefined) {
attributes = layer;
layer = 0;
}
if(layer >= this.getLayerCount() && layer < 0) {
throw new Error("layer does not exist");
}
if(typeof(attributes) == 'string') {
attributes = attributes.split(',');
}
for(var i = 0; i < attributes.length; ++i) {
attributes[i] = attributes[i].replace(/ /g, '');
}
this.layers[layer].options.interactivity = attributes;
this._definitionUpdated();
return this;
} | javascript | {
"resource": ""
} | |
q35482 | train | function(layer, style, version) {
if(version === undefined) {
version = style;
style = layer;
layer = 0;
}
version = version || cartodb.CARTOCSS_DEFAULT_VERSION;
this.layers[layer].options.cartocss = style;
this.layers[layer].options.cartocss_version = version;
this._definitionUpdated();
} | javascript | {
"resource": ""
} | |
q35483 | train | function(layer, b) {
// shift arguments to maintain caompatibility
if(b == undefined) {
b = layer;
layer = 0;
}
var layerInteraction;
this.interactionEnabled[layer] = b;
if(!b) {
layerInteraction = this.interaction[layer];
if(layerInteraction) {
layerInteraction.remove();
this.interaction[layer] = null;
}
} else {
// if urls is null it means that setInteraction will be called
// when the layergroup token was recieved, then the real interaction
// layer will be created
if(this.urls) {
// generate the tilejson from the urls. wax needs it
var layer_index = this.getLayerIndexByNumber(+layer);
var tilejson = this._tileJSONfromTiles(layer_index, this.urls);
// remove previous
layerInteraction = this.interaction[layer];
if(layerInteraction) {
layerInteraction.remove();
}
var self = this;
// add the new one
this.interaction[layer] = this.interactionClass()
.map(this.options.map)
.tilejson(tilejson)
.on('on', function(o) {
if (self._interactionDisabled) return;
o.layer = +layer;
self._manageOnEvents(self.options.map, o);
})
.on('off', function(o) {
if (self._interactionDisabled) return;
o = o || {}
o.layer = +layer;
self._manageOffEvents(self.options.map, o);
});
}
}
return this;
} | javascript | {
"resource": ""
} | |
q35484 | train | function() {
var xyz = {z: 4, x: 6, y: 6}
, self = this
, img = new Image()
, urls = this._tileJSON()
getTiles(function(urls) {
var grid_url = urls.tiles[0]
.replace(/\{z\}/g,xyz.z)
.replace(/\{x\}/g,xyz.x)
.replace(/\{y\}/g,xyz.y);
this.options.ajax({
method: "get",
url: grid_url,
crossDomain: true,
success: function() {
self.tilesOk();
clearTimeout(timeout)
},
error: function(xhr, msg, data) {
clearTimeout(timeout);
self.error(xhr.responseText && JSON.parse(xhr.responseText));
}
});
});
var timeout = setTimeout(function(){
clearTimeout(timeout);
self.error("tile timeout");
}, 30000);
} | javascript | {
"resource": ""
} | |
q35485 | train | function(container, className) {
// Check if any cartodb-logo exists within container
var a = [];
var re = new RegExp('\\b' + className + '\\b');
var els = container.getElementsByTagName("*");
for(var i=0,j=els.length; i<j; i++)
if(re.test(els[i].className))a.push(els[i]);
return a.length > 0;
} | javascript | {
"resource": ""
} | |
q35486 | train | function(position, timeout, container) {
var self = this;
setTimeout(function() {
if (!self.isWadusAdded(container, 'cartodb-logo')) {
var cartodb_link = document.createElement("div");
var is_retina = self.isRetinaBrowser();
cartodb_link.setAttribute('class','cartodb-logo');
cartodb_link.setAttribute('style',"position:absolute; bottom:0; left:0; display:block; border:none; z-index:1000000;");
var protocol = location.protocol.indexOf('https') === -1 ? 'http': 'https';
var link = cdb.config.get('cartodb_logo_link');
cartodb_link.innerHTML = "<a href='" + link + "' target='_blank'><img width='71' height='29' src='" + protocol + "://cartodb.s3.amazonaws.com/static/new_logo" + (is_retina ? '@2x' : '') + ".png' style='position:absolute; bottom:" +
( position.bottom || 0 ) + "px; left:" + ( position.left || 0 ) + "px; display:block; width:71px!important; height:29px!important; border:none; outline:none;' alt='CARTO' title='CARTO' />";
container.appendChild(cartodb_link);
}
},( timeout || 0 ));
} | javascript | {
"resource": ""
} | |
q35487 | train | function(layerModel, leafletLayer, leafletMap) {
this.leafletLayer = leafletLayer;
this.leafletMap = leafletMap;
this.model = layerModel;
this.setModel(layerModel);
this.type = layerModel.get('type') || layerModel.get('kind');
this.type = this.type.toLowerCase();
} | javascript | {
"resource": ""
} | |
q35488 | train | function (tilePoint) {
var EMPTY_GIF = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
this._adjustTilePoint(tilePoint);
var tiles = [EMPTY_GIF];
if(this.tilejson) {
tiles = this.tilejson.tiles;
}
var index = (tilePoint.x + tilePoint.y) % tiles.length;
return L.Util.template(tiles[index], L.Util.extend({
z: this._getZoomForUrl(),
x: tilePoint.x,
y: tilePoint.y
}, this.options));
} | javascript | {
"resource": ""
} | |
q35489 | train | function(opacity) {
if (isNaN(opacity) || opacity>1 || opacity<0) {
throw new Error(opacity + ' is not a valid value');
}
// Leaflet only accepts 0-0.99... Weird!
this.options.opacity = Math.min(opacity, 0.99);
if (this.options.visible) {
L.TileLayer.prototype.setOpacity.call(this, this.options.opacity);
this.fire('updated');
}
} | javascript | {
"resource": ""
} | |
q35490 | train | function(map) {
var self = this;
this.options.map = map;
// Add cartodb logo
if (this.options.cartodb_logo != false)
cdb.geo.common.CartoDBLogo.addWadus({ left:8, bottom:8 }, 0, map._container);
this.__update(function() {
// if while the layer was processed in the server is removed
// it should not be added to the map
var id = L.stamp(self);
if (!map._layers[id]) {
return;
}
L.TileLayer.prototype.onAdd.call(self, map);
self.fire('added');
self.options.added = true;
});
} | javascript | {
"resource": ""
} | |
q35491 | train | function(map) {
if(this.options.added) {
this.options.added = false;
L.TileLayer.prototype.onRemove.call(this, map);
}
} | javascript | {
"resource": ""
} | |
q35492 | train | function(done) {
var self = this;
this.fire('updated');
this.fire('loading');
var map = this.options.map;
this.getTiles(function(urls, err) {
if(urls) {
self.tilejson = urls;
self.setUrl(self.tilejson.tiles[0]);
// manage interaction
self._reloadInteraction();
self.ok && self.ok();
done && done();
} else {
self.error && self.error(err);
done && done();
}
});
} | javascript | {
"resource": ""
} | |
q35493 | train | function(attribution) {
this._checkLayer();
// Remove old one
this.map.attributionControl.removeAttribution(
cdb.core.sanitize.html(this.options.attribution)
);
// Change text
this.map.attributionControl.addAttribution(
cdb.core.sanitize.html(attribution)
);
// Set new attribution in the options
this.options.attribution = attribution;
// Change in the layer
this.tilejson.attribution = this.options.attribution;
this.fire('updated');
} | javascript | {
"resource": ""
} | |
q35494 | train | function(map, o) {
var layer_point = this._findPos(map,o);
if (!layer_point || isNaN(layer_point.x) || isNaN(layer_point.y)) {
// If layer_point doesn't contain x and y,
// we can't calculate event map position
return false;
}
var latlng = map.layerPointToLatLng(layer_point);
var event_type = o.e.type.toLowerCase();
var screenPos = map.layerPointToContainerPoint(layer_point);
switch (event_type) {
case 'mousemove':
if (this.options.featureOver) {
return this.options.featureOver(o.e,latlng, screenPos, o.data, o.layer);
}
break;
case 'click':
case 'touchend':
case 'touchmove': // for some reason android browser does not send touchend
case 'mspointerup':
case 'pointerup':
case 'pointermove':
if (this.options.featureClick) {
this.options.featureClick(o.e,latlng, screenPos, o.data, o.layer);
}
break;
default:
break;
}
} | javascript | {
"resource": ""
} | |
q35495 | train | function() {
var b = this.map_leaflet.getBounds();
var sw = b.getSouthWest();
var ne = b.getNorthEast();
return [
[sw.lat, sw.lng],
[ne.lat, ne.lng]
];
} | javascript | {
"resource": ""
} | |
q35496 | train | function(layerModel, gmapsLayer, gmapsMap) {
this.gmapsLayer = gmapsLayer;
this.map = this.gmapsMap = gmapsMap;
this.model = layerModel;
this.model.bind('change', this._update, this);
this.type = layerModel.get('type') || layerModel.get('kind');
this.type = this.type.toLowerCase();
} | javascript | {
"resource": ""
} | |
q35497 | train | function() {
var self = this;
var index = -1;
this.gmapsMap.overlayMapTypes.forEach(
function(layer, i) {
if (layer == self) {
index = i;
}
}
);
return index;
} | javascript | {
"resource": ""
} | |
q35498 | train | function() {
if(!this.isBase) {
var self = this;
var idx = this._searchLayerIndex();
if(idx >= 0) {
this.gmapsMap.overlayMapTypes.removeAt(idx);
} else if (this.gmapsLayer.setMap){
this.gmapsLayer.setMap(null);
}
this.model.unbind(null, null, this);
this.unbind();
}
} | javascript | {
"resource": ""
} | |
q35499 | train | function(layerModel, gmapsMap) {
var self = this;
_.bindAll(this, 'featureOut', 'featureOver', 'featureClick');
var opts = _.clone(layerModel.attributes);
opts.map = gmapsMap;
var // preserve the user's callbacks
_featureOver = opts.featureOver,
_featureOut = opts.featureOut,
_featureClick = opts.featureClick;
opts.featureOver = function() {
_featureOver && _featureOver.apply(this, arguments);
self.featureOver && self.featureOver.apply(this, arguments);
};
opts.featureOut = function() {
_featureOut && _featureOut.apply(this, arguments);
self.featureOut && self.featureOut.apply(this, arguments);
};
opts.featureClick = function() {
_featureClick && _featureClick.apply(this, arguments);
self.featureClick && self.featureClick.apply(opts, arguments);
};
cdb.geo.CartoDBLayerGMaps.call(this, opts);
cdb.geo.GMapsLayerView.call(this, layerModel, this, gmapsMap);
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.