_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q47800
baseForOwnRight
train
function baseForOwnRight(object, callback) { var props = keys(object), length = props.length; while (length--) { var key = props[length]; if (callback(object[key], key, object) === false) { break; } } return object; }
javascript
{ "resource": "" }
q47801
baseMerge
train
function baseMerge(object, source, callback, stackA, stackB) { (isArray(source) ? baseEach : baseForOwn)(source, function(source, key) { var found, isArr, result = source, value = object[key]; if (source && ((isArr = isArray(source)) || isPlainObject(source))) { // avoid merging previously merged cyclic sources var stackLength = stackA.length; while (stackLength--) { if ((found = stackA[stackLength] == source)) { value = stackB[stackLength]; break; } } if (!found) { var isShallow; if (callback) { result = callback(value, source); if ((isShallow = typeof result != 'undefined')) { value = result; } } if (!isShallow) { value = isArr ? (isArray(value) ? value : []) : (isPlainObject(value) ? value : {}); } // add `source` and associated `value` to the stack of traversed objects stackA.push(source); stackB.push(value); // recursively merge objects and arrays (susceptible to call stack limits) if (!isShallow) { baseMerge(value, source, callback, stackA, stackB); } } } else { if (callback) { result = callback(value, source); if (typeof result == 'undefined') { result = source; } } if (typeof result != 'undefined') { value = result; } } object[key] = value; }); }
javascript
{ "resource": "" }
q47802
createAggregator
train
function createAggregator(setter, retArray) { return function(collection, callback, thisArg) { var result = retArray ? [[], []] : {}; callback = lodash.createCallback(callback, thisArg, 3); if (isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { var value = collection[index]; setter(result, value, callback(value, index, collection), collection); } } else { baseEach(collection, function(value, key, collection) { setter(result, value, callback(value, key, collection), collection); }); } return result; }; }
javascript
{ "resource": "" }
q47803
createIterator
train
function createIterator(options) { options.shadowedProps = shadowedProps; options.support = support; // create the function factory var factory = Function( 'errorClass, errorProto, hasOwnProperty, isArguments, isObject, objectProto, ' + 'nonEnumProps, stringClass, stringProto, toString', 'return function(' + options.args + ') {\n' + iteratorTemplate(options) + '\n}' ); // return the compiled function return factory( errorClass, errorProto, hasOwnProperty, isArguments, isObject, objectProto, nonEnumProps, stringClass, stringProto, toString ); }
javascript
{ "resource": "" }
q47804
getHolders
train
function getHolders(array) { var index = -1, length = array.length, result = []; while (++index < length) { if (array[index] === lodash) { result.push(index); } } return result; }
javascript
{ "resource": "" }
q47805
sample
train
function sample(collection, n, guard) { if (collection && typeof collection.length != 'number') { collection = values(collection); } else if (support.unindexedChars && isString(collection)) { collection = collection.split(''); } if (n == null || guard) { return collection ? collection[baseRandom(0, collection.length - 1)] : undefined; } var result = shuffle(collection); result.length = nativeMin(nativeMax(0, n), result.length); return result; }
javascript
{ "resource": "" }
q47806
partialRight
train
function partialRight(func) { if (func) { var arity = func[expando] ? func[expando][2] : func.length, partialRightArgs = slice(arguments, 1); arity -= partialRightArgs.length; } return createWrapper(func, PARTIAL_RIGHT_FLAG, arity, null, null, partialRightArgs); }
javascript
{ "resource": "" }
q47807
functions
train
function functions(object) { var result = []; baseForIn(object, function(value, key) { if (isFunction(value)) { result.push(key); } }); return result.sort(); }
javascript
{ "resource": "" }
q47808
matches
train
function matches(source) { source || (source = {}); var props = keys(source), key = props[0], a = source[key]; // fast path the common case of providing an object with a single // property containing a primitive value if (props.length == 1 && a === a && !isObject(a)) { return function(object) { if (!hasOwnProperty.call(object, key)) { return false; } var b = object[key]; return a === b && (a !== 0 || (1 / a == 1 / b)); }; } return function(object) { var length = props.length, result = false; while (length--) { var key = props[length]; if (!(result = hasOwnProperty.call(object, key) && baseIsEqual(object[key], source[key], null, true))) { break; } } return result; }; }
javascript
{ "resource": "" }
q47809
mixin
train
function mixin(object, source, options) { var chain = true, methodNames = source && functions(source); if (!source || (!options && !methodNames.length)) { if (options == null) { options = source; } source = object; object = lodash; methodNames = functions(source); } if (options === false) { chain = false; } else if (isObject(options) && 'chain' in options) { chain = options.chain; } var index = -1, isFunc = isFunction(object), length = methodNames ? methodNames.length : 0; while (++index < length) { var methodName = methodNames[index], func = object[methodName] = source[methodName]; if (isFunc) { object.prototype[methodName] = (function(func) { return function() { var chainAll = this.__chain__, value = this.__wrapped__, args = [value]; push.apply(args, arguments); var result = func.apply(object, args); if (chain || chainAll) { if (value === result && isObject(result)) { return this; } result = new object(result); result.__chain__ = chainAll; } return result; }; }(func)); } } }
javascript
{ "resource": "" }
q47810
result
train
function result(object, key, defaultValue) { var value = object == null ? undefined : object[key]; if (typeof value == 'undefined') { return defaultValue; } return isFunction(value) ? object[key]() : value; }
javascript
{ "resource": "" }
q47811
train
function(obj, name, callback) { var listeningTo = this._listeningTo; if (!listeningTo) return this; var remove = !name && !callback; if (!callback && typeof name === 'object') callback = this; if (obj) (listeningTo = {})[obj.cid] = obj; for (var id in listeningTo) { obj = listeningTo[id]; obj.off(name, callback, this); if (remove || _.isEmpty(obj._events)) delete this._listeningTo[id]; } return this; }
javascript
{ "resource": "" }
q47812
train
function(namespace, key) { key = JSON.stringify(key); return "cache_" + configs.revision + "_" + namespace + "_" + key; }
javascript
{ "resource": "" }
q47813
train
function(namespace, key) { var ckey = Cache.key(namespace, key); var ctime = (new Date()).getTime(); var v = Storage.get(ckey); if (v == null) { return null; } else { if (v.expiration == -1 || v.expiration > ctime) { return v.value; } else { Storage.remove(ckey); return null; } } }
javascript
{ "resource": "" }
q47814
train
function(namespace, key) { var ckey = Cache.key(namespace, key); var ctime = (new Date()).getTime(); Storage.remove(ckey); }
javascript
{ "resource": "" }
q47815
train
function(namespace, key, value, expiration) { var ckey = Cache.key(namespace, key); var ctime = (new Date()).getTime(); if (expiration > 0) { expiration = ctime + expiration * 1000; } else { expiration = -1; } Storage.set(ckey, { "expiration": expiration, "value": value }); return Cache.get(key); }
javascript
{ "resource": "" }
q47816
train
function() { var s = Storage.storage(); if (s == null) { return false; } Object.keys(s).forEach(function(key){ if (/^(cache_)/.test(key)) { s.removeItem(key); } }); }
javascript
{ "resource": "" }
q47817
train
function(namespace) { var ncache = {}; _.each(cache_methods, function(method) { ncache[method] = _.partial(Cache[method], namespace); }) return ncache; }
javascript
{ "resource": "" }
q47818
train
function() { if (!this.available) return; if (window.applicationCache.status === window.applicationCache.UPDATEREADY) { this.trigger("update"); } return window.applicationCache.status === window.applicationCache.UPDATEREADY; }
javascript
{ "resource": "" }
q47819
train
function(state) { if (state == this.state) return; this.state = state; logging.log("state ", this.state); this.trigger("state", this.state); }
javascript
{ "resource": "" }
q47820
train
function(title) { if (this._preTitle.length > 0) title = this._preTitle + " " + title; if (_.size(title) == 0) return this.app.name; return title + " - " + this.app.name; }
javascript
{ "resource": "" }
q47821
train
function(name, value, metaName) { if (_.isObject(name)) { _.each(name, function(value, name) { this.meta(name, value); }, this); return; } if (metaName == null) metaName = "name"; var mt = this.$('meta['+metaName+'="'+name+'"]'); if (mt.length === 0) { mt = $("<meta>", {}).attr(metaName, name).appendTo('head'); } if (value != null) { mt.attr('content', value); return this; } else { return mt.attr('content'); } }
javascript
{ "resource": "" }
q47822
train
function(rel, href, mimetype) { if (_.isObject(rel)) { _.each(rel, function(value, name) { this.link(name, value); }, this); return; } var mt = this.$('link[rel="'+rel+'"]'); if (mt.length === 0) { mt = $("<link>", {}).attr("rel", rel).appendTo(this.$el); } if (mimetype != null) mt.attr("type", mimetype); if (href != null) { mt.attr('href', href); } else { return mt.attr('href'); } }
javascript
{ "resource": "" }
q47823
train
function(value, absolute) { var mt = this.$('title'); if (mt.length === 0) { mt = $("<title>", {}).appendTo(this.$el); } if (value != null) { this._title = value; if (absolute !== false) value = this.completeTitle(value); mt.text(value); } else { return mt.attr('content'); } }
javascript
{ "resource": "" }
q47824
train
function(index, follow) { if (_.isNull(follow)) follow = index; var value = ""; value = index ? "index" : "noindex"; value = value + "," + (follow ? "follow" : "nofollow"); this.meta("robots", value); return this; }
javascript
{ "resource": "" }
q47825
train
function() { if (this.started) { logging.warn("routing history already started"); return false; } var self = this; var $window = $(window); var rootUrl = document.location.protocol+'//'+(document.location.hostname||document.location.host); logging.log("start routing history"); $window.bind('hashchange', _.bind(this._handleCurrentState, this)); var ret = this._handleCurrentState(); this.started = true; return ret; }
javascript
{ "resource": "" }
q47826
train
function(route, args) { url = urls.route(route, args); logging.log("navigate to ", url); window.location.hash = url; return this; }
javascript
{ "resource": "" }
q47827
train
function(route, name) { var handler; if (_.isObject(route) && !_.isRegExp(route)) { _.each(route, function(callback, route) { this.route(route, callback); }, this); return this; } handler = this[name]; if (handler == null) { handler = function() { var args = _.values(arguments); args.unshift('route:'+name); this.trigger.apply(this, args); }; } /** * Router controller for this application * * @property router * @type {Router} */ if (!this.router) this.router = new this.Router(); this.router.route(route, name, _.bind(handler, this)); return this; }
javascript
{ "resource": "" }
q47828
train
function(models, options) { options = _.defaults(options || {}, { totalCount: false }); // Manage {list:[], n:0} for infinite list if (_.size(models) == 2 && models.list != null && models.n != null) { this._totalCount = models.n; return this.reset(models.list, options); } // Remove reference for (var i = 0, length = this.models.length; i < length; i++) { this._removeReference(this.models[i], options); } options.previousModels = this.models; this.options.startIndex = 0; this.models = []; this._byId = {}; if (options.totalCount) this._totalCount = null; this.add(models, _.extend({silent: true}, options || {})); options = _.defaults(options || {}, { silent: false }); if (!options.silent) this.trigger('reset', this, options); return this; }
javascript
{ "resource": "" }
q47829
train
function(model, options) { var index; if (_.isArray(model)) { _.each(model, function(m) { this.remove(m, options); }, this); return this; } options = _.defaults(options || {}, { silent: false }); model = this._prepareModel(model); _.each(this.models, function(m, i) { if (!m || model.id == m.id) { this.models.splice(i, 1); index = i; return; } }, this); delete this._byId[model.id]; if (options.silent) return this; options.index = index; if (this._totalCount != null) this._totalCount = _.max([0, this._totalCount - 1]); this.trigger('remove', model, this, options); this._removeReference(model); return this; }
javascript
{ "resource": "" }
q47830
train
function(model, options) { model = this._prepareModel(model, options); this.add(model, options); return model; }
javascript
{ "resource": "" }
q47831
train
function(options) { this.queue.defer(function() { options = _.defaults(options || {}, { refresh: false }); var d, self = this; if (this.options.loader == null) return this; if (options.refresh) { this.options.startIndex = 0; this._totalCount = null; this.reset([]); } if (this._totalCount == null || this.hasMore() > 0 || options.refresh) { this.options.startIndex = this.options.startIndex || 0; d = Q(this[this.options.loader].apply(this, this.options.loaderArgs || [])); d.done(function() { self.options.startIndex = self.options.startIndex + self.options.limit }); } else { d = Q.reject(); } return d; }, this); return this; }
javascript
{ "resource": "" }
q47832
train
function(method, properties) { if (this.methods[method]) throw "Method already define for this backend: "+method; properties.id = method; properties.regexp = this.routeToRegExp(method); this.methods[method] = properties; return this; }
javascript
{ "resource": "" }
q47833
train
function(method, sId) { sId = sId || method; sId = this.options.prefix+"."+sId; return this.addMethod(method, { fallback: function(args, options, method) { return Storage.get(sId+"."+method); }, after: function(args, results, options, method) { Storage.set(sId+"."+method, results); } }); }
javascript
{ "resource": "" }
q47834
train
function(method) { return _.find(this.methods, function(handler) { return handler.regexp.test(method); }) || this.defaultHandler; }
javascript
{ "resource": "" }
q47835
train
function(method, args, options) { var that = this, methodHandler; options = options || {}; var handler = this.getHandler(method); if (!handler) return Q.reject(new Error("No handler found for method: "+method)); // Is offline if (!Offline.isConnected()) { methodHandler = handler.fallback; } methodHandler = methodHandler || handler.execute || this.defaultHandler.execute; // No default if (!methodHandler) { return Q.reject(new Error("No handler found for this method in this backend")); } return Q(methodHandler(args, options, method)).then(function(results) { if (handler.after) { return Q.all([ Q(handler.after(args, results, options, method)), Q((that.defaultHandler.after || function() {})(args, results, options, method)) ]).then(function() { return Q(results); }, function() { return Q(results); }); } return results; }); }
javascript
{ "resource": "" }
q47836
train
function (url, protocol, hostname, port) { var match = text.xdRegExp.exec(url), uProtocol, uHostName, uPort; if (!match) { return true; } uProtocol = match[2]; uHostName = match[3]; uHostName = uHostName.split(':'); uPort = uHostName[1]; uHostName = uHostName[0]; return (!uProtocol || uProtocol === protocol) && (!uHostName || uHostName === hostname) && ((!uPort && !uHostName) || uPort === port); }
javascript
{ "resource": "" }
q47837
train
function(cls, options) { var d = Q.defer(); cls = cls || DialogView; var diag = new cls(options); diag.once("close", function(result, e) { if (result != null) { d.resolve(result); } else { d.reject(result); } }); setTimeout(function() { d.notify(diag); }, 1); diag.update(); return d.promise; }
javascript
{ "resource": "" }
q47838
train
function(title, message, defaultmsg) { return Dialogs.open(null, { "title": title, "message": message, "dialog": "prompt", "default": defaultmsg, "autoFocus": true, "valueSelector": "selectorPrompt" }); }
javascript
{ "resource": "" }
q47839
train
function(title, message, choices, defaultChoice) { return Dialogs.open(null, { "title": title, "message": message, "dialog": "select", "default": defaultChoice, "choices": choices, "autoFocus": true, "valueSelector": "selectorPrompt" }); }
javascript
{ "resource": "" }
q47840
train
function(title, message) { if (!message) { message = title; title = null; } return Dialogs.open(null, { "title": title, "message": message, "dialog": "confirm" }); }
javascript
{ "resource": "" }
q47841
train
function(err) { Dialogs.alert("Error:", err.message || err); console.error(err.stack || err.message || err); return Q.reject(err); }
javascript
{ "resource": "" }
q47842
dfl
train
function dfl(a, b, c) { switch (arguments.length) { case 2: return a != null ? a : b; case 3: return a != null ? a : b != null ? b : c; default: throw new Error("Implement me"); } }
javascript
{ "resource": "" }
q47843
setProjection
train
function setProjection( element, options ) { var width = options.width || element.offsetWidth; var height = options.height || element.offsetHeight; var projection, path; if ( options && typeof options.scope === 'undefined') { options.scope = 'world'; } if ( options.scope === 'usa' ) { projection = d3.geo.albersUsa() .scale(width) .translate([width / 2, height / 2]); } else if ( options.scope === 'world' ) { projection = d3.geo[options.projection]() .scale((width + 1) / 2 / Math.PI) .translate([width / 2, height / (options.projection === "mercator" ? 1.45 : 1.8)]); } path = d3.geo.path() .projection( projection ); return {path: path, projection: projection}; }
javascript
{ "resource": "" }
q47844
addLegend
train
function addLegend(layer, data, options) { data = data || {}; if ( !this.options.fills ) { return; } var html = '<dl>'; var label = ''; if ( data.legendTitle ) { html = '<h2>' + data.legendTitle + '</h2>' + html; } for ( var fillKey in this.options.fills ) { if ( fillKey === 'defaultFill') { if (! data.defaultFillName ) { continue; } label = data.defaultFillName; } else { if (data.labels && data.labels[fillKey]) { label = data.labels[fillKey]; } else { label= fillKey + ': '; } } html += '<dt>' + label + '</dt>'; html += '<dd style="background-color:' + this.options.fills[fillKey] + '">&nbsp;</dd>'; } html += '</dl>'; var hoverover = d3.select( this.options.element ).append('div') .attr('class', 'datamaps-legend') .html(html); }
javascript
{ "resource": "" }
q47845
defaults
train
function defaults(obj) { Array.prototype.slice.call(arguments, 1).forEach(function(source) { if (source) { for (var prop in source) { if (obj[prop] == null) obj[prop] = source[prop]; } } }); return obj; }
javascript
{ "resource": "" }
q47846
train
function(data) { var that = this; data = data || this.toJSON(); return api.execute("put:report/"+this.get("id"), data) .then(function(_data) { that.set(_data); return that; }); }
javascript
{ "resource": "" }
q47847
train
function() { var that = this; return api.execute("get:alerts") .then(function(data) { console.log("alerts", data); that.reset(data); return that; }); }
javascript
{ "resource": "" }
q47848
train
function(r) { r = r.toJSON? r.toJSON() : r; this.report.del("visualizations", { silent: true }); this.report.set(r); hr.History.navigate("report/"+this.report.get("id")); }
javascript
{ "resource": "" }
q47849
train
function() { var that = this; return that.reports.loadAll() .then(function() { return dialogs.select( i18n.t("reports.select.title"), i18n.t("reports.select.message"), _.object(that.reports.map(function(r) { return [ r.get("id"), r.get("title") ] })), that.report.get("id") ); }) .then(function(rId) { hr.History.navigate("report/"+rId); }); }
javascript
{ "resource": "" }
q47850
train
function() { var that = this; return dialogs.fields(i18n.t("reports.create.title"), { "title": { label: i18n.t("reports.create.fields.title"), type: "text" } }) .then(function(args) { return that.reports.create(args); }); }
javascript
{ "resource": "" }
q47851
train
function() { var that = this; return dialogs.fields(i18n.t("reports.edit.title"), { "title": { label: i18n.t("reports.edit.fields.title"), type: "text" } }, this.report.toJSON()) .then(function(data) { return that.report.edit(data); }); }
javascript
{ "resource": "" }
q47852
train
function() { var that = this; return dialogs.confirm(i18n.t("reports.remove.title")) .then(function() { return that.report.remove(); }) .then(function() { that.report.clear(); return that.reports.loadAll(); }) .then(function() { that.update(); }) .fail(dialogs.error); }
javascript
{ "resource": "" }
q47853
train
function() { var that = this; return api.execute("get:types") .then(function(types) { return dialogs.fields(i18n.t("visualization.create.title"), { "eventName": { 'label': i18n.t("visualization.create.fields.eventName"), 'type': "select", 'options': _.chain(types) .map(function(type) { return [type.type, type.type]; }) .object() .value() }, "type": { 'label': i18n.t("visualization.create.fields.type"), 'type': "select", 'options': _.chain(allVisualizations) .map(function(visualization, vId) { return [ vId, visualization.title ]; }) .object() .value() } }) }) .then(function(data) { that.report.visualizations.add(data); return that.report.edit().fail(dialogs.error); }); }
javascript
{ "resource": "" }
q47854
train
function(e) { if (e) e.preventDefault(); var that = this; return api.execute("get:types") .fail(dialogs.error) .then(function(events) { return dialogs.fields(i18n.t("alerts.create.title"), { "title": { "label": i18n.t("alerts.create.fields.title.label"), "type": "text" }, "eventName": { 'label': i18n.t("alerts.create.fields.eventName.label"), 'type': "select", 'options': _.chain(events) .map(function(type) { return [type.type, type.type]; }) .object() .value() }, "type": { 'label': i18n.t("alerts.create.fields.type.label"), 'type': "select", 'options': _.chain(allAlerts) .map(function(a, aId) { return [aId, a.title]; }) .object() .value() }, "interval": { "label": i18n.t("alerts.create.fields.interval.label"), "type": "number", 'min': 1, 'default': 1, 'help': i18n.t("alerts.create.fields.interval.help") }, "condition": { "label": i18n.t("alerts.create.fields.condition.label"), "type": "text", "help": i18n.t("alerts.create.fields.condition.help") }, }); }) .then(function(data) { return that.alerts.create({ 'title': data.title, 'condition': data.condition, 'eventName': data.eventName, 'interval': data.interval, 'type': data.type }) .then(that.manageAlerts.bind(that), dialogs.error) }); }
javascript
{ "resource": "" }
q47855
parseArgs
train
function parseArgs () { // Configure the argument parser yargs .option("schema", { type: "boolean", default: true, }) .option("spec", { type: "boolean", default: true, }) .option("o", { alias: "outfile", type: "string", normalize: true, }) .option("r", { alias: "dereference", type: "boolean", }) .option("t", { alias: "type", type: "string", normalize: true, default: "json", }) .option("f", { alias: "format", type: "number", default: 2, }) .option("w", { alias: "wrap", type: "number", default: Infinity, }) .option("d", { alias: "debug", type: "boolean", }) .option("h", { alias: "help", type: "boolean", }); // Show the version number on "--version" or "-v" yargs .version() .alias("v", "version"); // Disable the default "--help" behavior yargs.help(false); // Parse the command-line arguments let args = yargs.argv; // Normalize the parsed arguments let parsed = { command: args._[0], file: args._[1], options: { schema: args.schema, spec: args.spec, outfile: args.outfile, dereference: args.dereference, format: args.format || 2, type: args.type || "json", wrap: args.wrap || Infinity, debug: args.debug, help: args.help, } }; if (parsed.options.debug) { console.log(JSON.stringify(parsed, null, 2)); } return parsed; }
javascript
{ "resource": "" }
q47856
bundle
train
function bundle (file, options) { api.bundle(file, options) .then((bundled) => { if (options.outfile) { console.log("Created %s from %s", options.outfile, file); } else { // Write the bundled API to stdout console.log(bundled); } }) .catch(errorHandler); }
javascript
{ "resource": "" }
q47857
errorHandler
train
function errorHandler (err) { let errorMessage = process.env.DEBUG ? err.stack : err.message; console.error(chalk.red(errorMessage)); process.exit(1); }
javascript
{ "resource": "" }
q47858
toYAML
train
function toYAML (api, spaces, wrap) { const jsYaml = require("js-yaml"); return jsYaml.dump(api, { indent: spaces, lineWidth: wrap, noRefs: true }); }
javascript
{ "resource": "" }
q47859
makeBundleJS
train
function makeBundleJS(psModule) { const bundleOutput = psModule.options.bundleOutput; const name = psModule.name; const srcDir = psModule.srcDir; const escaped = jsStringEscape(path.relative(srcDir, bundleOutput)); const result = `module.exports = require("${escaped}")["${name}"]`; return Promise.resolve(result); }
javascript
{ "resource": "" }
q47860
makeJS
train
function makeJS(psModule, psModuleMap, js) { const requireRE = /require\(['"]\.\.\/([\w\.]+)(?:\/index\.js)?['"]\)/g; const foreignRE = /require\(['"]\.\/foreign(?:\.js)?['"]\)/g; const name = psModule.name; const imports = psModuleMap[name].imports; var replacedImports = []; const result = js .replace(requireRE, (m, p1) => { const moduleValue = psModuleMap[p1]; if (!moduleValue) { debug('module %s was not found in the map, replacing require with null', p1); return 'null'; } else { const escapedPath = jsStringEscape(moduleValue.src); replacedImports.push(p1); return `require("${escapedPath}")`; } }) .replace(foreignRE, () => { const escapedPath = jsStringEscape(psModuleMap[name].ffi); return `require("${escapedPath}")`; }) ; const additionalImports = difference(imports, replacedImports); if (!additionalImports.length) { return Promise.resolve(result); } else { debug('rebuilding module map due to additional imports for %s: %o', name, additionalImports); psModule.cache.psModuleMap = null; return updatePsModuleMap(psModule).then(updatedPsModuleMap => { const additionalImportsResult = additionalImports.map(import_ => { const moduleValue = updatedPsModuleMap[import_]; if (!moduleValue) { debug('module %s was not found in the map, skipping require', import_); return null; } else { const escapedPath = jsStringEscape(moduleValue.src); return `var ${import_.replace(/\./g, '_')} = require("${escapedPath}")`; } }).filter(a => a !== null).join('\n'); return result + '\n' + additionalImportsResult; }); } }
javascript
{ "resource": "" }
q47861
addClass
train
function addClass(className) { if (typeof className === 'undefined') { return this; } const classes = className.split(' '); for (let i = 0; i < classes.length; i += 1) { for (let j = 0; j < this.length; j += 1) { if (typeof this[j] !== 'undefined' && typeof this[j].classList !== 'undefined') this[j].classList.add(classes[i]); } } return this; }
javascript
{ "resource": "" }
q47862
transform
train
function transform(transform) { for (let i = 0; i < this.length; i += 1) { const elStyle = this[i].style; elStyle.webkitTransform = transform; elStyle.transform = transform; } return this; }
javascript
{ "resource": "" }
q47863
each
train
function each(callback) { // Don't bother continuing without a callback if (!callback) return this; // Iterate over the current collection for (let i = 0; i < this.length; i += 1) { // If the callback returns false if (callback.call(this[i], i, this[i]) === false) { // End the loop early return this; } } // Return `this` to allow chained DOM operations return this; }
javascript
{ "resource": "" }
q47864
train
function (el, e) { var value = can.trim(el.val()); if (e.keyCode === ENTER_KEY && value !== '') { new Models.Todo({ text : value, complete : false }).save(function () { el.val(''); }); } }
javascript
{ "resource": "" }
q47865
train
function (list, e, item) { this.options.todos.push(item); // Reset the filter so that you always see your new todo this.options.state.attr('filter', ''); }
javascript
{ "resource": "" }
q47866
train
function () { // Remove the `selected` class from the old link and add it to the link for the current location hash this.element.find('#filters').find('a').removeClass('selected') .end().find('[href="' + window.location.hash + '"]').addClass('selected'); }
javascript
{ "resource": "" }
q47867
train
function (el) { var value = can.trim(el.val()), todo = el.closest('.todo').data('todo'); // If we don't have a todo we don't need to do anything if (!todo) { return; } if (value === '') { todo.destroy(); } else { todo.attr({ editing : false, text : value }).save(); } }
javascript
{ "resource": "" }
q47868
train
function (el) { var toggle = el.prop('checked'); can.each(this.options.todos, function (todo) { todo.attr('complete', toggle).save(); }); }
javascript
{ "resource": "" }
q47869
train
function () { for (var i = this.options.todos.length - 1, todo; i > -1 && (todo = this.options.todos[i]); i--) { if (todo.attr('complete')) { todo.destroy(); } } }
javascript
{ "resource": "" }
q47870
train
function( type, options, element ) { options || (options = {}); var create = Syn.create, setup = create[type] && create[type].setup, kind = key.test(type) ? 'key' : (page.test(type) ? "page" : "mouse"), createType = create[type] || {}, createKind = create[kind], event, ret, autoPrevent, dispatchEl = element; //any setup code? Syn.support.ready === 2 && setup && setup(type, options, element); autoPrevent = options._autoPrevent; //get kind delete options._autoPrevent; if ( createType.event ) { ret = createType.event(type, options, element); } else { //convert options options = createKind.options ? createKind.options(type, options, element) : options; if (!Syn.support.changeBubbles && /option/i.test(element.nodeName) ) { dispatchEl = element.parentNode; //jQuery expects clicks on select } //create the event event = createKind.event(type, options, dispatchEl); //send the event ret = Syn.dispatch(event, dispatchEl, type, autoPrevent); } ret && Syn.support.ready === 2 && Syn.defaults[type] && Syn.defaults[type].call(element, options, autoPrevent); return ret; }
javascript
{ "resource": "" }
q47871
train
function( type, options, element ) { //check if options is character or has character options = typeof options != "object" ? { character: options } : options; //don't change the orignial options = h.extend({}, options) if ( options.character ) { h.extend(options, Syn.key.options(options.character, type)); delete options.character; } options = h.extend({ ctrlKey: !! Syn.key.ctrlKey, altKey: !! Syn.key.altKey, shiftKey: !! Syn.key.shiftKey, metaKey: !! Syn.key.metaKey }, options) return options; }
javascript
{ "resource": "" }
q47872
train
function (elems, context) { var oldFragment = $.buildFragment, ret; elems = [elems]; // Set context per 1.8 logic context = context || document; context = !context.nodeType && context[0] || context; context = context.ownerDocument || context; ret = oldFragment.call(jQuery, elems, context); return ret.cacheable ? $.clone(ret.fragment) : ret.fragment || ret; }
javascript
{ "resource": "" }
q47873
train
function (content) { // Convert bad values into empty strings var isInvalid = content === null || content === undefined || (isNaN(content) && ("" + content === 'NaN')); return ("" + (isInvalid ? '' : content)).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(strQuote, '&#34;').replace(strSingleQuote, "&#39;"); }
javascript
{ "resource": "" }
q47874
train
function (s) { return s.replace(strColons, '/').replace(strWords, '$1_$2').replace(strLowUp, '$1_$2').replace(strDash, '_').toLowerCase(); }
javascript
{ "resource": "" }
q47875
train
function (str, data, remove) { var obs = []; obs.push(str.replace(strReplacer, function (whole, inside) { // Convert inside to type. var ob = can.getObject(inside, data, remove === undefined ? remove : !remove); if (ob === undefined) { obs = null; return ""; } // If a container, push into objs (which will return objects found). if (isContainer(ob) && obs) { obs.push(ob); return ""; } return "" + ob; })); return obs === null ? obs : (obs.length <= 1 ? obs[0] : obs); }
javascript
{ "resource": "" }
q47876
train
function (result) { var frag = can.buildFragment(result, document.body); // If we have an empty frag... if (!frag.childNodes.length) { frag.appendChild(document.createTextNode('')); } return frag; }
javascript
{ "resource": "" }
q47877
train
function (src) { return can.map(src.toString().split(/\/|\./g), function (part) { // Dont include empty strings in toId functions if (part) { return part; } }).join("_"); }
javascript
{ "resource": "" }
q47878
train
function (url, async) { var suffix = url.match(/\.[\w\d]+$/), type, // If we are reading a script element for the content of the template, // `el` will be set to that script element. el, // A unique identifier for the view (used for caching). // This is typically derived from the element id or // the url for the template. id, // The ajax request used to retrieve the template content. jqXHR; //If the url has a #, we assume we want to use an inline template //from a script element and not current page's HTML if (url.match(/^#/)) { url = url.substr(1); } // If we have an inline template, derive the suffix from the `text/???` part. // This only supports `<script>` tags. if (el = document.getElementById(url)) { suffix = "." + el.type.match(/\/(x\-)?(.+)/)[2]; } // If there is no suffix, add one. if (!suffix && !$view.cached[url]) { url += (suffix = $view.ext); } if (can.isArray(suffix)) { suffix = suffix[0] } // Convert to a unique and valid id. id = $view.toId(url); // If an absolute path, use `steal` to get it. // You should only be using `//` if you are using `steal`. if (url.match(/^\/\//)) { var sub = url.substr(2); url = !window.steal ? sub : steal.config().root.mapJoin(sub); } // Set the template engine type. type = $view.types[suffix]; // If it is cached, if ($view.cached[id]) { // Return the cached deferred renderer. return $view.cached[id]; // Otherwise if we are getting this from a `<script>` element. } else if (el) { // Resolve immediately with the element's `innerHTML`. return $view.registerView(id, el.innerHTML, type); } else { // Make an ajax request for text. var d = new can.Deferred(); can.ajax({ async: async, url: url, dataType: "text", error: function (jqXHR) { checkText("", url); d.reject(jqXHR); }, success: function (text) { // Make sure we got some text back. checkText(text, url); $view.registerView(id, text, type, d) } }); return d; } }
javascript
{ "resource": "" }
q47879
train
function () { for (var name in observing) { var ob = observing[name]; ob.observe.obj.unbind(ob.observe.attr, onchanged); delete observing[name]; } }
javascript
{ "resource": "" }
q47880
train
function (ev) { // If the compute is no longer bound (because the same change event led to an unbind) // then do not call getValueAndBind, or we will leak bindings. if (computeState && !computeState.bound) { return; } if (ev.batchNum === undefined || ev.batchNum !== batchNum) { // store the old value var oldValue = data.value, // get the new value newvalue = getValueAndBind(); // update the value reference (in case someone reads) data.value = newvalue; // if a change happened if (newvalue !== oldValue) { callback(newvalue, oldValue); } batchNum = batchNum = ev.batchNum; } }
javascript
{ "resource": "" }
q47881
train
function () { var info = getValueAndObserved(getterSetter, context), newObserveSet = info.observed; var value = info.value; matched = !matched; // go through every attribute read by this observe can.each(newObserveSet, function (ob) { // if the observe/attribute pair is being observed if (observing[ob.obj._cid + "|" + ob.attr]) { // mark at as observed observing[ob.obj._cid + "|" + ob.attr].matched = matched; } else { // otherwise, set the observe/attribute on oldObserved, marking it as being observed observing[ob.obj._cid + "|" + ob.attr] = { matched: matched, observe: ob }; ob.obj.bind(ob.attr, onchanged); } }); // Iterate through oldObserved, looking for observe/attributes // that are no longer being bound and unbind them for (var name in observing) { var ob = observing[name]; if (ob.matched !== matched) { ob.observe.obj.unbind(ob.observe.attr, onchanged); delete observing[name]; } } return value; }
javascript
{ "resource": "" }
q47882
train
function (el, parentNode) { // updates the text of the text node update = function (newVal) { node.nodeValue = "" + newVal; teardownCheck(node.parentNode); }; var parent = getParentNode(el, parentNode), node = document.createTextNode(binding.value); // When iterating through an Observe.List with no DOM // elements containing the individual items, the parent // is sometimes incorrect not the true parent of the // source element. (#153) if (el.parentNode !== parent) { parent = el.parentNode; parent.insertBefore(node, el); parent.removeChild(el); } else { parent.insertBefore(node, el); parent.removeChild(el); } setupTeardownOnDestroy(parent); }
javascript
{ "resource": "" }
q47883
train
function (span, parentNode) { // updates the elements with the new content update = function (newVal) { // is this still part of the DOM? var attached = nodes[0].parentNode; // update the nodes in the DOM with the new rendered value if (attached) { makeAndPut(newVal); } teardownCheck(nodes[0].parentNode); }; // make sure we have a valid parentNode parentNode = getParentNode(span, parentNode); // A helper function to manage inserting the contents // and removing the old contents var nodes, makeAndPut = function (val) { // create the fragment, but don't hook it up // we need to insert it into the document first var frag = can.view.frag(val, parentNode), // keep a reference to each node newNodes = can.makeArray(frag.childNodes), last = nodes ? nodes[nodes.length - 1] : span; // Insert it in the `document` or `documentFragment` if (last.nextSibling) { last.parentNode.insertBefore(frag, last.nextSibling); } else { last.parentNode.appendChild(frag); } // nodes hasn't been set yet if (!nodes) { can.remove(can.$(span)); nodes = newNodes; // set the teardown nodeList nodeList = nodes; can.view.registerNode(nodes); } else { // Update node Array's to point to new nodes // and then remove the old nodes. // It has to be in this order for Mootools // and IE because somehow, after an element // is removed from the DOM, it loses its // expando values. var nodesToRemove = can.makeArray(nodes); can.view.replace(nodes, newNodes); can.remove(can.$(nodesToRemove)); } }; // nodes are the nodes that any updates will replace // at this point, these nodes could be part of a documentFragment makeAndPut(binding.value, [span]); setupTeardownOnDestroy(parentNode); //children have to be properly nested HTML for buildFragment to work properly }
javascript
{ "resource": "" }
q47884
train
function (val) { // create the fragment, but don't hook it up // we need to insert it into the document first var frag = can.view.frag(val, parentNode), // keep a reference to each node newNodes = can.makeArray(frag.childNodes), last = nodes ? nodes[nodes.length - 1] : span; // Insert it in the `document` or `documentFragment` if (last.nextSibling) { last.parentNode.insertBefore(frag, last.nextSibling); } else { last.parentNode.appendChild(frag); } // nodes hasn't been set yet if (!nodes) { can.remove(can.$(span)); nodes = newNodes; // set the teardown nodeList nodeList = nodes; can.view.registerNode(nodes); } else { // Update node Array's to point to new nodes // and then remove the old nodes. // It has to be in this order for Mootools // and IE because somehow, after an element // is removed from the DOM, it loses its // expando values. var nodesToRemove = can.makeArray(nodes); can.view.replace(nodes, newNodes); can.remove(can.$(nodesToRemove)); } }
javascript
{ "resource": "" }
q47885
getStartDate
train
function getStartDate(date, minDate, maxDate) { let startDate = startOfDay(date); if (minDate) { const minDateNormalized = startOfDay(minDate); if (isBefore(startDate, minDateNormalized)) { startDate = minDateNormalized; } } if (maxDate) { const maxDateNormalized = startOfDay(maxDate); if (isBefore(maxDateNormalized, startDate)) { startDate = maxDateNormalized; } } return startDate; }
javascript
{ "resource": "" }
q47886
fillFrontWeek
train
function fillFrontWeek({ firstDayOfMonth, minDate, maxDate, selectedDates, firstDayOfWeek, showOutsideDays }) { const dates = []; let firstDay = (firstDayOfMonth.getDay() + 7 - firstDayOfWeek) % 7; if (showOutsideDays) { const lastDayOfPrevMonth = addDays(firstDayOfMonth, -1); const prevDate = lastDayOfPrevMonth.getDate(); const prevDateMonth = lastDayOfPrevMonth.getMonth(); const prevDateYear = lastDayOfPrevMonth.getFullYear(); // Fill out front week for days from // preceding month with dates from previous month. let counter = 0; while (counter < firstDay) { const date = new Date(prevDateYear, prevDateMonth, prevDate - counter); const dateObj = { date, selected: isSelected(selectedDates, date), selectable: isSelectable(minDate, maxDate, date), today: false, prevMonth: true, nextMonth: false }; dates.unshift(dateObj); counter++; } } else { // Fill out front week for days from // preceding month with buffer. while (firstDay > 0) { dates.unshift(''); firstDay--; } } return dates; }
javascript
{ "resource": "" }
q47887
fillBackWeek
train
function fillBackWeek({ lastDayOfMonth, minDate, maxDate, selectedDates, firstDayOfWeek, showOutsideDays }) { const dates = []; let lastDay = (lastDayOfMonth.getDay() + 7 - firstDayOfWeek) % 7; if (showOutsideDays) { const firstDayOfNextMonth = addDays(lastDayOfMonth, 1); const nextDateMonth = firstDayOfNextMonth.getMonth(); const nextDateYear = firstDayOfNextMonth.getFullYear(); // Fill out back week for days from // following month with dates from next month. let counter = 0; while (counter < 6 - lastDay) { const date = new Date(nextDateYear, nextDateMonth, 1 + counter); const dateObj = { date, selected: isSelected(selectedDates, date), selectable: isSelectable(minDate, maxDate, date), today: false, prevMonth: false, nextMonth: true }; dates.push(dateObj); counter++; } } else { // Fill out back week for days from // following month with buffer. while (lastDay < 6) { dates.push(''); lastDay++; } } return dates; }
javascript
{ "resource": "" }
q47888
getWeeks
train
function getWeeks(dates) { const weeksLength = Math.ceil(dates.length / 7); const weeks = []; for (let i = 0; i < weeksLength; i++) { weeks[i] = []; for (let x = 0; x < 7; x++) { weeks[i].push(dates[i * 7 + x]); } } return weeks; }
javascript
{ "resource": "" }
q47889
isSelected
train
function isSelected(selectedDates, date) { selectedDates = Array.isArray(selectedDates) ? selectedDates : [selectedDates]; return selectedDates.some(selectedDate => { if ( selectedDate instanceof Date && startOfDay(selectedDate).getTime() === startOfDay(date).getTime() ) { return true; } return false; }); }
javascript
{ "resource": "" }
q47890
isSelectable
train
function isSelectable(minDate, maxDate, date) { if ( (minDate && isBefore(date, minDate)) || (maxDate && isBefore(maxDate, date)) ) { return false; } return true; }
javascript
{ "resource": "" }
q47891
extendPreventingOverrides
train
function extendPreventingOverrides (a, b) { Object.keys(b).forEach(addContentFromBtoA) return a function addContentFromBtoA (key) { if (a.hasOwnProperty(key)) { mergeIntoAnArray(a, b, key) } else { a[key] = b[key] } } }
javascript
{ "resource": "" }
q47892
t
train
function t (template, data) { for (var key in data) { template = template.replace(new RegExp('{' + key + '}', 'g'), data[key] || '') } return template }
javascript
{ "resource": "" }
q47893
getValuesAsList
train
function getValuesAsList(value) { return ( value .replace(/ +/g, ' ') // remove all extraneous spaces .split(' ') .map(i => i.trim()) // get rid of extra space before/after each item .filter(Boolean) // get rid of empty strings // join items which are within parenthese // luckily `calc (100% - 5px)` is invalid syntax and it must be `calc(100% - 5px)`, otherwise this would be even more complex .reduce( ({list, state}, item) => { const openParansCount = (item.match(/\(/g) || []).length const closedParansCount = (item.match(/\)/g) || []).length if (state.parensDepth > 0) { list[list.length - 1] = `${list[list.length - 1]} ${item}` } else { list.push(item) } state.parensDepth += openParansCount - closedParansCount return {list, state} }, {list: [], state: {parensDepth: 0}}, ).list ) }
javascript
{ "resource": "" }
q47894
handleQuartetValues
train
function handleQuartetValues(value) { const splitValues = getValuesAsList(value) if (splitValues.length <= 3 || splitValues.length > 4) { return value } const [top, right, bottom, left] = splitValues return [top, left, bottom, right].join(' ') }
javascript
{ "resource": "" }
q47895
convert
train
function convert(object) { return Object.keys(object).reduce((newObj, originalKey) => { let originalValue = object[originalKey] if (isString(originalValue)) { // you're welcome to later code 😺 originalValue = originalValue.trim() } // Some properties should never be transformed if (includes(propsToIgnore, originalKey)) { newObj[originalKey] = originalValue return newObj } const {key, value} = convertProperty(originalKey, originalValue) newObj[key] = value return newObj }, Array.isArray(object) ? [] : {}) }
javascript
{ "resource": "" }
q47896
convertProperty
train
function convertProperty(originalKey, originalValue) { const isNoFlip = /\/\*\s?@noflip\s?\*\//.test(originalValue) const key = isNoFlip ? originalKey : getPropertyDoppelganger(originalKey) const value = isNoFlip ? originalValue : getValueDoppelganger(key, originalValue) return {key, value} }
javascript
{ "resource": "" }
q47897
getValueDoppelganger
train
function getValueDoppelganger(key, originalValue) { /* eslint complexity:[2, 9] */ // let's try to keep the complexity down... If we have to do this much more, let's break this up if (isNullOrUndefined(originalValue) || isBoolean(originalValue)) { return originalValue } if (isObject(originalValue)) { return convert(originalValue) // recurssion 🌀 } const isNum = isNumber(originalValue) const importantlessValue = isNum ? originalValue : originalValue.replace(/ !important.*?$/, '') const isImportant = !isNum && importantlessValue.length !== originalValue.length const valueConverter = propertyValueConverters[key] let newValue if (valueConverter) { newValue = valueConverter({ value: importantlessValue, valuesToConvert, isRtl: true, bgImgDirectionRegex, bgPosDirectionRegex, }) } else { newValue = valuesToConvert[importantlessValue] || importantlessValue } if (isImportant) { return `${newValue} !important` } return newValue }
javascript
{ "resource": "" }
q47898
selectOSTab
train
function selectOSTab(target, osName) { // Declare all variables var i, tabcontent, tablinks; // Get all elements with class="tabcontent" and hide them tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } // Get all elements with class="tablinks" and remove the class "active" tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } // Show the current tab, and add an "active" class to the link that opened the tab document.getElementById(osName).style.display = "block"; target.className += " active"; }
javascript
{ "resource": "" }
q47899
showSignUpForm
train
function showSignUpForm() { var modal = document.getElementById('downloadModal'); // Make sure modal is in the body, not where it was originally deployed. $("body").append($(modal)) // Get the button that opens the modal var btn = document.getElementById("downloadBtn"); // Get the <span> element that closes the modal var span = document.getElementsByClassName("close")[0]; // When the user clicks on the button, open the modal modal.style.display = "block"; // When the user clicks on <span> (x), close the modal span.onclick = function () { modal.style.display = "none"; } // When the user clicks anywhere outside of the modal, close it window.onclick = function (event) { if (event.target == modal) { modal.style.display = "none"; } } }
javascript
{ "resource": "" }