id int32 0 58k | repo stringlengths 5 67 | path stringlengths 4 116 | func_name stringlengths 0 58 | original_string stringlengths 52 373k | language stringclasses 1 value | code stringlengths 52 373k | code_tokens list | docstring stringlengths 4 11.8k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 86 226 |
|---|---|---|---|---|---|---|---|---|---|---|---|
32,900 | building5/sails-db-migrate | lib/sailsDbMigrate.js | parseSailsConfig | function parseSailsConfig(sailsConfig) {
var res = {};
var connection;
if (!sailsConfig.migrations) {
throw new Error('Migrations not configured. Please setup ./config/migrations.js');
}
var connectionName = sailsConfig.migrations.connection;
if (!connectionName) {
throw new Error('connection missing from ./config/migrations.js');
}
connection = sailsConfig.connections[connectionName];
if (!connection) {
throw new Error('could not find connection ' + connectionName + ' in ./config/connections.js');
}
// build the db url, which contains the password
res.url = buildURL(connection);
// check for ssl option in connection config
if (connection.ssl) {
res.adapter = connection.adapter;
res.ssl = true;
}
// now build a clean one for logging, without the password
if (connection.password != null) {
connection.password = '****';
}
res.cleanURL = buildURL(connection);
return res;
} | javascript | function parseSailsConfig(sailsConfig) {
var res = {};
var connection;
if (!sailsConfig.migrations) {
throw new Error('Migrations not configured. Please setup ./config/migrations.js');
}
var connectionName = sailsConfig.migrations.connection;
if (!connectionName) {
throw new Error('connection missing from ./config/migrations.js');
}
connection = sailsConfig.connections[connectionName];
if (!connection) {
throw new Error('could not find connection ' + connectionName + ' in ./config/connections.js');
}
// build the db url, which contains the password
res.url = buildURL(connection);
// check for ssl option in connection config
if (connection.ssl) {
res.adapter = connection.adapter;
res.ssl = true;
}
// now build a clean one for logging, without the password
if (connection.password != null) {
connection.password = '****';
}
res.cleanURL = buildURL(connection);
return res;
} | [
"function",
"parseSailsConfig",
"(",
"sailsConfig",
")",
"{",
"var",
"res",
"=",
"{",
"}",
";",
"var",
"connection",
";",
"if",
"(",
"!",
"sailsConfig",
".",
"migrations",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Migrations not configured. Please setup ./config... | Parse out the database URL from the sails config.
@param sailsConfig Sails config object.
@returns {object} .url and .cleanURL for the database connection.
@throws Error if adapter is not supported. | [
"Parse",
"out",
"the",
"database",
"URL",
"from",
"the",
"sails",
"config",
"."
] | 41ffc849446f433298fe23dbccee771c1a55137f | https://github.com/building5/sails-db-migrate/blob/41ffc849446f433298fe23dbccee771c1a55137f/lib/sailsDbMigrate.js#L72-L105 |
32,901 | building5/sails-db-migrate | lib/gruntTasks.js | buildDbMigrateArgs | function buildDbMigrateArgs(grunt, config, command) {
var args = [];
var name = grunt.option('name');
args.push(command);
if (command === 'create') {
if (!name) {
throw new Error('--name required to create migration');
}
args.push(name);
}
if (grunt.option('count') !== undefined) {
args.push('--count');
args.push(grunt.option('count'));
}
if (grunt.option('dry-run')) {
args.push('--dry-run');
}
if (grunt.option('db-verbose')) {
args.push('--verbose');
}
if (grunt.option('sql-file')) {
args.push('--sql-file');
}
if (grunt.option('coffee-file')) {
args.push('--coffee-file');
} else if (config.coffeeFile) {
args.push('--coffee-file');
}
if (grunt.option('migrations-dir')) {
args.push('--migrations-dir');
args.push(grunt.option('migrations-dir'));
} else if (config.migrationsDir) {
args.push('--migrations-dir');
args.push(config.migrationsDir);
}
if (grunt.option('table')) {
args.push('--table');
args.push(grunt.option('table'));
} else if (config.table) {
args.push('--table');
args.push(config.table);
}
return args;
} | javascript | function buildDbMigrateArgs(grunt, config, command) {
var args = [];
var name = grunt.option('name');
args.push(command);
if (command === 'create') {
if (!name) {
throw new Error('--name required to create migration');
}
args.push(name);
}
if (grunt.option('count') !== undefined) {
args.push('--count');
args.push(grunt.option('count'));
}
if (grunt.option('dry-run')) {
args.push('--dry-run');
}
if (grunt.option('db-verbose')) {
args.push('--verbose');
}
if (grunt.option('sql-file')) {
args.push('--sql-file');
}
if (grunt.option('coffee-file')) {
args.push('--coffee-file');
} else if (config.coffeeFile) {
args.push('--coffee-file');
}
if (grunt.option('migrations-dir')) {
args.push('--migrations-dir');
args.push(grunt.option('migrations-dir'));
} else if (config.migrationsDir) {
args.push('--migrations-dir');
args.push(config.migrationsDir);
}
if (grunt.option('table')) {
args.push('--table');
args.push(grunt.option('table'));
} else if (config.table) {
args.push('--table');
args.push(config.table);
}
return args;
} | [
"function",
"buildDbMigrateArgs",
"(",
"grunt",
",",
"config",
",",
"command",
")",
"{",
"var",
"args",
"=",
"[",
"]",
";",
"var",
"name",
"=",
"grunt",
".",
"option",
"(",
"'name'",
")",
";",
"args",
".",
"push",
"(",
"command",
")",
";",
"if",
"(... | Builds the command line arguments to pass to db-migrate.
@param grunt Grunt object.
@param command The db-migrate command to run.
@returns Arguments array for the db-migrate command. | [
"Builds",
"the",
"command",
"line",
"arguments",
"to",
"pass",
"to",
"db",
"-",
"migrate",
"."
] | 41ffc849446f433298fe23dbccee771c1a55137f | https://github.com/building5/sails-db-migrate/blob/41ffc849446f433298fe23dbccee771c1a55137f/lib/gruntTasks.js#L13-L66 |
32,902 | building5/sails-db-migrate | lib/gruntTasks.js | usage | function usage(grunt) {
grunt.log.writeln('usage: grunt db:migrate[:up|:down|:create] [options]');
grunt.log.writeln(' See ./migrations/README.md for more details');
grunt.log.writeln();
grunt.log.writeln('db:migrate:create Options:');
grunt.log.writeln(' --name=NAME Name of the migration to create');
grunt.log.writeln();
grunt.log.writeln('db:migrate[:up|:down] Options:');
grunt.log.writeln(' --count=N Max number of migrations to run.');
grunt.log.writeln(' --dry-run Prints the SQL but doesn\'t run it.');
grunt.log.writeln(' --db-verbose Verbose mode.');
grunt.log.writeln(' --sql-file Create sql files for up and down.');
grunt.log.writeln(' --coffee-file Create a coffeescript migration file.');
grunt.log.writeln(' --migrations-dir The directory to use for migration files.');
grunt.log.writeln(' Defaults to "migrations".');
grunt.log.writeln(' --table Specify the table to track migrations in.');
grunt.log.writeln(' Defaults to "migrations".');
} | javascript | function usage(grunt) {
grunt.log.writeln('usage: grunt db:migrate[:up|:down|:create] [options]');
grunt.log.writeln(' See ./migrations/README.md for more details');
grunt.log.writeln();
grunt.log.writeln('db:migrate:create Options:');
grunt.log.writeln(' --name=NAME Name of the migration to create');
grunt.log.writeln();
grunt.log.writeln('db:migrate[:up|:down] Options:');
grunt.log.writeln(' --count=N Max number of migrations to run.');
grunt.log.writeln(' --dry-run Prints the SQL but doesn\'t run it.');
grunt.log.writeln(' --db-verbose Verbose mode.');
grunt.log.writeln(' --sql-file Create sql files for up and down.');
grunt.log.writeln(' --coffee-file Create a coffeescript migration file.');
grunt.log.writeln(' --migrations-dir The directory to use for migration files.');
grunt.log.writeln(' Defaults to "migrations".');
grunt.log.writeln(' --table Specify the table to track migrations in.');
grunt.log.writeln(' Defaults to "migrations".');
} | [
"function",
"usage",
"(",
"grunt",
")",
"{",
"grunt",
".",
"log",
".",
"writeln",
"(",
"'usage: grunt db:migrate[:up|:down|:create] [options]'",
")",
";",
"grunt",
".",
"log",
".",
"writeln",
"(",
"' See ./migrations/README.md for more details'",
")",
";",
"grunt",
... | Display command usage information.
@param grunt Grunt object. | [
"Display",
"command",
"usage",
"information",
"."
] | 41ffc849446f433298fe23dbccee771c1a55137f | https://github.com/building5/sails-db-migrate/blob/41ffc849446f433298fe23dbccee771c1a55137f/lib/gruntTasks.js#L73-L90 |
32,903 | anvaka/ngraph.asyncforce | lib/layoutWorker.js | handleMessageFromMainThread | function handleMessageFromMainThread(message) {
var kind = message.data.kind;
var payload = message.data.payload;
if (kind === messageKind.init) {
graph = fromjson(payload.graph);
var options = JSON.parse(payload.options);
init(graph, options);
} else if (kind === messageKind.step) {
step();
} else if (kind === messageKind.pinNode) {
pinNode(payload.nodeId, payload.isPinned);
} else if (kind === messageKind.setNodePosition) {
setNodePosition(payload.nodeId, payload.x, payload.y, payload.z);
}
// TODO: listen for graph changes from main thread and update layout here.
} | javascript | function handleMessageFromMainThread(message) {
var kind = message.data.kind;
var payload = message.data.payload;
if (kind === messageKind.init) {
graph = fromjson(payload.graph);
var options = JSON.parse(payload.options);
init(graph, options);
} else if (kind === messageKind.step) {
step();
} else if (kind === messageKind.pinNode) {
pinNode(payload.nodeId, payload.isPinned);
} else if (kind === messageKind.setNodePosition) {
setNodePosition(payload.nodeId, payload.x, payload.y, payload.z);
}
// TODO: listen for graph changes from main thread and update layout here.
} | [
"function",
"handleMessageFromMainThread",
"(",
"message",
")",
"{",
"var",
"kind",
"=",
"message",
".",
"data",
".",
"kind",
";",
"var",
"payload",
"=",
"message",
".",
"data",
".",
"payload",
";",
"if",
"(",
"kind",
"===",
"messageKind",
".",
"init",
"... | public API is over. Below are private methods only. | [
"public",
"API",
"is",
"over",
".",
"Below",
"are",
"private",
"methods",
"only",
"."
] | 98cc8f87074f61d36215b672f0b31855b4deca4a | https://github.com/anvaka/ngraph.asyncforce/blob/98cc8f87074f61d36215b672f0b31855b4deca4a/lib/layoutWorker.js#L26-L43 |
32,904 | rintoj/statex | dist/core/decorators.js | bindData | function bindData(target, key, selector) {
return state_1.State.select(selector).subscribe(function (args) {
if (typeof target.setState === 'function') {
var state = {};
state[key] = args;
target.setState(state);
}
if (typeof target[key] === 'function')
return target[key].call(target, args);
target[key] = args;
});
} | javascript | function bindData(target, key, selector) {
return state_1.State.select(selector).subscribe(function (args) {
if (typeof target.setState === 'function') {
var state = {};
state[key] = args;
target.setState(state);
}
if (typeof target[key] === 'function')
return target[key].call(target, args);
target[key] = args;
});
} | [
"function",
"bindData",
"(",
"target",
",",
"key",
",",
"selector",
")",
"{",
"return",
"state_1",
".",
"State",
".",
"select",
"(",
"selector",
")",
".",
"subscribe",
"(",
"function",
"(",
"args",
")",
"{",
"if",
"(",
"typeof",
"target",
".",
"setStat... | Bind data for give key and target using a selector function
@param {any} target
@param {any} key
@param {any} selectorFunc | [
"Bind",
"data",
"for",
"give",
"key",
"and",
"target",
"using",
"a",
"selector",
"function"
] | 19d2a321587c67ee6ff406251ea3d6b3eeaa3418 | https://github.com/rintoj/statex/blob/19d2a321587c67ee6ff406251ea3d6b3eeaa3418/dist/core/decorators.js#L13-L24 |
32,905 | rintoj/statex | dist/core/decorators.js | action | function action(targetAction) {
return function (target, propertyKey, descriptor) {
if (targetAction == undefined) {
var metadata = Reflect.getMetadata('design:paramtypes', target, propertyKey);
if (metadata == undefined || metadata.length < 2)
throw new Error('@action() must be applied to a function with two arguments. ' +
'eg: reducer(state: State, action: SubclassOfAction): State { }');
targetAction = metadata[1];
}
var statexActions = {};
if (Reflect.hasMetadata(constance_1.STATEX_ACTION_KEY, target)) {
statexActions = Reflect.getMetadata(constance_1.STATEX_ACTION_KEY, target);
}
statexActions[propertyKey] = targetAction;
Reflect.defineMetadata(constance_1.STATEX_ACTION_KEY, statexActions, target);
return {
value: function (state, payload) {
return descriptor.value.call(this, state, payload);
}
};
};
} | javascript | function action(targetAction) {
return function (target, propertyKey, descriptor) {
if (targetAction == undefined) {
var metadata = Reflect.getMetadata('design:paramtypes', target, propertyKey);
if (metadata == undefined || metadata.length < 2)
throw new Error('@action() must be applied to a function with two arguments. ' +
'eg: reducer(state: State, action: SubclassOfAction): State { }');
targetAction = metadata[1];
}
var statexActions = {};
if (Reflect.hasMetadata(constance_1.STATEX_ACTION_KEY, target)) {
statexActions = Reflect.getMetadata(constance_1.STATEX_ACTION_KEY, target);
}
statexActions[propertyKey] = targetAction;
Reflect.defineMetadata(constance_1.STATEX_ACTION_KEY, statexActions, target);
return {
value: function (state, payload) {
return descriptor.value.call(this, state, payload);
}
};
};
} | [
"function",
"action",
"(",
"targetAction",
")",
"{",
"return",
"function",
"(",
"target",
",",
"propertyKey",
",",
"descriptor",
")",
"{",
"if",
"(",
"targetAction",
"==",
"undefined",
")",
"{",
"var",
"metadata",
"=",
"Reflect",
".",
"getMetadata",
"(",
"... | Binds action to a function
@example
class TodoStore {
@action
addTodo(state: State, action: AddTodoAction): State {
// return modified state
}
}
@export
@param {*} target
@param {string} propertyKey
@param {PropertyDescriptor} descriptor
@returns | [
"Binds",
"action",
"to",
"a",
"function"
] | 19d2a321587c67ee6ff406251ea3d6b3eeaa3418 | https://github.com/rintoj/statex/blob/19d2a321587c67ee6ff406251ea3d6b3eeaa3418/dist/core/decorators.js#L44-L65 |
32,906 | rintoj/statex | dist/core/decorators.js | subscribe | function subscribe(propsClass) {
var _this = this;
var dataBindings = Reflect.getMetadata(constance_1.STATEX_DATA_BINDINGS_KEY, propsClass || this);
if (dataBindings != undefined) {
var selectors_1 = dataBindings.selectors || {};
dataBindings.subscriptions = (dataBindings.subscriptions || []).concat(Object.keys(selectors_1).map(function (key) { return ({
target: _this,
subscription: bindData(_this, key, selectors_1[key])
}); }));
Reflect.defineMetadata(constance_1.STATEX_DATA_BINDINGS_KEY, dataBindings, this);
}
} | javascript | function subscribe(propsClass) {
var _this = this;
var dataBindings = Reflect.getMetadata(constance_1.STATEX_DATA_BINDINGS_KEY, propsClass || this);
if (dataBindings != undefined) {
var selectors_1 = dataBindings.selectors || {};
dataBindings.subscriptions = (dataBindings.subscriptions || []).concat(Object.keys(selectors_1).map(function (key) { return ({
target: _this,
subscription: bindData(_this, key, selectors_1[key])
}); }));
Reflect.defineMetadata(constance_1.STATEX_DATA_BINDINGS_KEY, dataBindings, this);
}
} | [
"function",
"subscribe",
"(",
"propsClass",
")",
"{",
"var",
"_this",
"=",
"this",
";",
"var",
"dataBindings",
"=",
"Reflect",
".",
"getMetadata",
"(",
"constance_1",
".",
"STATEX_DATA_BINDINGS_KEY",
",",
"propsClass",
"||",
"this",
")",
";",
"if",
"(",
"dat... | Subscribe to the state events and map it to properties
@export | [
"Subscribe",
"to",
"the",
"state",
"events",
"and",
"map",
"it",
"to",
"properties"
] | 19d2a321587c67ee6ff406251ea3d6b3eeaa3418 | https://github.com/rintoj/statex/blob/19d2a321587c67ee6ff406251ea3d6b3eeaa3418/dist/core/decorators.js#L99-L110 |
32,907 | rintoj/statex | dist/core/decorators.js | unsubscribe | function unsubscribe() {
var _this = this;
var dataBindings = Reflect.getMetadata(constance_1.STATEX_DATA_BINDINGS_KEY, this);
if (dataBindings != undefined) {
var subscriptions = dataBindings.subscriptions || [];
subscriptions.forEach(function (item) { return item.target === _this && item.subscription != undefined && item.subscription.unsubscribe(); });
dataBindings.subscriptions = subscriptions.filter(function (item) { return item.target !== _this; });
Reflect.defineMetadata(constance_1.STATEX_DATA_BINDINGS_KEY, dataBindings, this);
}
} | javascript | function unsubscribe() {
var _this = this;
var dataBindings = Reflect.getMetadata(constance_1.STATEX_DATA_BINDINGS_KEY, this);
if (dataBindings != undefined) {
var subscriptions = dataBindings.subscriptions || [];
subscriptions.forEach(function (item) { return item.target === _this && item.subscription != undefined && item.subscription.unsubscribe(); });
dataBindings.subscriptions = subscriptions.filter(function (item) { return item.target !== _this; });
Reflect.defineMetadata(constance_1.STATEX_DATA_BINDINGS_KEY, dataBindings, this);
}
} | [
"function",
"unsubscribe",
"(",
")",
"{",
"var",
"_this",
"=",
"this",
";",
"var",
"dataBindings",
"=",
"Reflect",
".",
"getMetadata",
"(",
"constance_1",
".",
"STATEX_DATA_BINDINGS_KEY",
",",
"this",
")",
";",
"if",
"(",
"dataBindings",
"!=",
"undefined",
"... | Unsubscribe from the state changes
@export | [
"Unsubscribe",
"from",
"the",
"state",
"changes"
] | 19d2a321587c67ee6ff406251ea3d6b3eeaa3418 | https://github.com/rintoj/statex/blob/19d2a321587c67ee6ff406251ea3d6b3eeaa3418/dist/core/decorators.js#L117-L126 |
32,908 | leifoolsen/mdl-ext | demo/scripts/dialog-polyfill.js | function() {
if (!this.openAsModal_) { return; }
this.openAsModal_ = false;
this.dialog_.style.zIndex = '';
// This won't match the native <dialog> exactly because if the user set top on a centered
// polyfill dialog, that top gets thrown away when the dialog is closed. Not sure it's
// possible to polyfill this perfectly.
if (this.replacedStyleTop_) {
this.dialog_.style.top = '';
this.replacedStyleTop_ = false;
}
// Clear the backdrop and remove from the manager.
this.backdrop_.parentNode && this.backdrop_.parentNode.removeChild(this.backdrop_);
dialogPolyfill.dm.removeDialog(this);
} | javascript | function() {
if (!this.openAsModal_) { return; }
this.openAsModal_ = false;
this.dialog_.style.zIndex = '';
// This won't match the native <dialog> exactly because if the user set top on a centered
// polyfill dialog, that top gets thrown away when the dialog is closed. Not sure it's
// possible to polyfill this perfectly.
if (this.replacedStyleTop_) {
this.dialog_.style.top = '';
this.replacedStyleTop_ = false;
}
// Clear the backdrop and remove from the manager.
this.backdrop_.parentNode && this.backdrop_.parentNode.removeChild(this.backdrop_);
dialogPolyfill.dm.removeDialog(this);
} | [
"function",
"(",
")",
"{",
"if",
"(",
"!",
"this",
".",
"openAsModal_",
")",
"{",
"return",
";",
"}",
"this",
".",
"openAsModal_",
"=",
"false",
";",
"this",
".",
"dialog_",
".",
"style",
".",
"zIndex",
"=",
"''",
";",
"// This won't match the native <di... | Remove this dialog from the modal top layer, leaving it as a non-modal. | [
"Remove",
"this",
"dialog",
"from",
"the",
"modal",
"top",
"layer",
"leaving",
"it",
"as",
"a",
"non",
"-",
"modal",
"."
] | a22a7be564ff81a41e94eb14bda6cd36401dc962 | https://github.com/leifoolsen/mdl-ext/blob/a22a7be564ff81a41e94eb14bda6cd36401dc962/demo/scripts/dialog-polyfill.js#L161-L177 | |
32,909 | leifoolsen/mdl-ext | demo/scripts/dialog-polyfill.js | function() {
// Find element with `autofocus` attribute, or fall back to the first form/tabindex control.
var target = this.dialog_.querySelector('[autofocus]:not([disabled])');
if (!target && this.dialog_.tabIndex >= 0) {
target = this.dialog_;
}
if (!target) {
// Note that this is 'any focusable area'. This list is probably not exhaustive, but the
// alternative involves stepping through and trying to focus everything.
var opts = ['button', 'input', 'keygen', 'select', 'textarea'];
var query = opts.map(function(el) {
return el + ':not([disabled])';
});
// TODO(samthor): tabindex values that are not numeric are not focusable.
query.push('[tabindex]:not([disabled]):not([tabindex=""])'); // tabindex != "", not disabled
target = this.dialog_.querySelector(query.join(', '));
}
safeBlur(document.activeElement);
target && target.focus();
} | javascript | function() {
// Find element with `autofocus` attribute, or fall back to the first form/tabindex control.
var target = this.dialog_.querySelector('[autofocus]:not([disabled])');
if (!target && this.dialog_.tabIndex >= 0) {
target = this.dialog_;
}
if (!target) {
// Note that this is 'any focusable area'. This list is probably not exhaustive, but the
// alternative involves stepping through and trying to focus everything.
var opts = ['button', 'input', 'keygen', 'select', 'textarea'];
var query = opts.map(function(el) {
return el + ':not([disabled])';
});
// TODO(samthor): tabindex values that are not numeric are not focusable.
query.push('[tabindex]:not([disabled]):not([tabindex=""])'); // tabindex != "", not disabled
target = this.dialog_.querySelector(query.join(', '));
}
safeBlur(document.activeElement);
target && target.focus();
} | [
"function",
"(",
")",
"{",
"// Find element with `autofocus` attribute, or fall back to the first form/tabindex control.",
"var",
"target",
"=",
"this",
".",
"dialog_",
".",
"querySelector",
"(",
"'[autofocus]:not([disabled])'",
")",
";",
"if",
"(",
"!",
"target",
"&&",
"... | Focuses on the first focusable element within the dialog. This will always blur the current
focus, even if nothing within the dialog is found. | [
"Focuses",
"on",
"the",
"first",
"focusable",
"element",
"within",
"the",
"dialog",
".",
"This",
"will",
"always",
"blur",
"the",
"current",
"focus",
"even",
"if",
"nothing",
"within",
"the",
"dialog",
"is",
"found",
"."
] | a22a7be564ff81a41e94eb14bda6cd36401dc962 | https://github.com/leifoolsen/mdl-ext/blob/a22a7be564ff81a41e94eb14bda6cd36401dc962/demo/scripts/dialog-polyfill.js#L223-L242 | |
32,910 | leifoolsen/mdl-ext | demo/scripts/dialog-polyfill.js | function(opt_returnValue) {
if (!this.dialog_.hasAttribute('open')) {
throw new Error('Failed to execute \'close\' on dialog: The element does not have an \'open\' attribute, and therefore cannot be closed.');
}
this.setOpen(false);
// Leave returnValue untouched in case it was set directly on the element
if (opt_returnValue !== undefined) {
this.dialog_.returnValue = opt_returnValue;
}
// Triggering "close" event for any attached listeners on the <dialog>.
var closeEvent = new supportCustomEvent('close', {
bubbles: false,
cancelable: false
});
this.dialog_.dispatchEvent(closeEvent);
} | javascript | function(opt_returnValue) {
if (!this.dialog_.hasAttribute('open')) {
throw new Error('Failed to execute \'close\' on dialog: The element does not have an \'open\' attribute, and therefore cannot be closed.');
}
this.setOpen(false);
// Leave returnValue untouched in case it was set directly on the element
if (opt_returnValue !== undefined) {
this.dialog_.returnValue = opt_returnValue;
}
// Triggering "close" event for any attached listeners on the <dialog>.
var closeEvent = new supportCustomEvent('close', {
bubbles: false,
cancelable: false
});
this.dialog_.dispatchEvent(closeEvent);
} | [
"function",
"(",
"opt_returnValue",
")",
"{",
"if",
"(",
"!",
"this",
".",
"dialog_",
".",
"hasAttribute",
"(",
"'open'",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Failed to execute \\'close\\' on dialog: The element does not have an \\'open\\' attribute, and therefo... | Closes this HTMLDialogElement. This is optional vs clearing the open
attribute, however this fires a 'close' event.
@param {string=} opt_returnValue to use as the returnValue | [
"Closes",
"this",
"HTMLDialogElement",
".",
"This",
"is",
"optional",
"vs",
"clearing",
"the",
"open",
"attribute",
"however",
"this",
"fires",
"a",
"close",
"event",
"."
] | a22a7be564ff81a41e94eb14bda6cd36401dc962 | https://github.com/leifoolsen/mdl-ext/blob/a22a7be564ff81a41e94eb14bda6cd36401dc962/demo/scripts/dialog-polyfill.js#L312-L329 | |
32,911 | rintoj/statex | dist/core/store.js | store | function store() {
return function (storeClass) {
// save a reference to the original constructor
var original = storeClass;
// a utility function to generate instances of a class
function construct(constructor, args) {
var dynamicClass = function () {
return new (constructor.bind.apply(constructor, [void 0].concat(args)))();
};
dynamicClass.prototype = constructor.prototype;
return new dynamicClass();
}
// the new constructor behavior
var overriddenConstructor = function Store() {
var _this = this;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (!Reflect.hasMetadata(constance_1.STATEX_ACTION_KEY, this))
return;
var statexActions = Reflect.getMetadata(constance_1.STATEX_ACTION_KEY, this);
Object.keys(statexActions).forEach(function (name) { return new statexActions[name]().subscribe(_this[name], _this); });
return construct(original, args);
};
// copy prototype so instanceof operator still works
overriddenConstructor.prototype = original.prototype;
// create singleton instance
var instance = new overriddenConstructor();
// return new constructor (will override original)
return instance && overriddenConstructor;
};
} | javascript | function store() {
return function (storeClass) {
// save a reference to the original constructor
var original = storeClass;
// a utility function to generate instances of a class
function construct(constructor, args) {
var dynamicClass = function () {
return new (constructor.bind.apply(constructor, [void 0].concat(args)))();
};
dynamicClass.prototype = constructor.prototype;
return new dynamicClass();
}
// the new constructor behavior
var overriddenConstructor = function Store() {
var _this = this;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (!Reflect.hasMetadata(constance_1.STATEX_ACTION_KEY, this))
return;
var statexActions = Reflect.getMetadata(constance_1.STATEX_ACTION_KEY, this);
Object.keys(statexActions).forEach(function (name) { return new statexActions[name]().subscribe(_this[name], _this); });
return construct(original, args);
};
// copy prototype so instanceof operator still works
overriddenConstructor.prototype = original.prototype;
// create singleton instance
var instance = new overriddenConstructor();
// return new constructor (will override original)
return instance && overriddenConstructor;
};
} | [
"function",
"store",
"(",
")",
"{",
"return",
"function",
"(",
"storeClass",
")",
"{",
"// save a reference to the original constructor",
"var",
"original",
"=",
"storeClass",
";",
"// a utility function to generate instances of a class",
"function",
"construct",
"(",
"cons... | This decorator configure instance of a store
@export
@param {*} storeClass
@returns | [
"This",
"decorator",
"configure",
"instance",
"of",
"a",
"store"
] | 19d2a321587c67ee6ff406251ea3d6b3eeaa3418 | https://github.com/rintoj/statex/blob/19d2a321587c67ee6ff406251ea3d6b3eeaa3418/dist/core/store.js#L11-L43 |
32,912 | rintoj/statex | dist/core/store.js | Store | function Store() {
var _this = this;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (!Reflect.hasMetadata(constance_1.STATEX_ACTION_KEY, this))
return;
var statexActions = Reflect.getMetadata(constance_1.STATEX_ACTION_KEY, this);
Object.keys(statexActions).forEach(function (name) { return new statexActions[name]().subscribe(_this[name], _this); });
return construct(original, args);
} | javascript | function Store() {
var _this = this;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (!Reflect.hasMetadata(constance_1.STATEX_ACTION_KEY, this))
return;
var statexActions = Reflect.getMetadata(constance_1.STATEX_ACTION_KEY, this);
Object.keys(statexActions).forEach(function (name) { return new statexActions[name]().subscribe(_this[name], _this); });
return construct(original, args);
} | [
"function",
"Store",
"(",
")",
"{",
"var",
"_this",
"=",
"this",
";",
"var",
"args",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"_i",
"=",
"0",
";",
"_i",
"<",
"arguments",
".",
"length",
";",
"_i",
"++",
")",
"{",
"args",
"[",
"_i",
"]",
"=",
... | the new constructor behavior | [
"the",
"new",
"constructor",
"behavior"
] | 19d2a321587c67ee6ff406251ea3d6b3eeaa3418 | https://github.com/rintoj/statex/blob/19d2a321587c67ee6ff406251ea3d6b3eeaa3418/dist/core/store.js#L24-L35 |
32,913 | rintoj/statex | dist/core/state.js | select | function select(state, selector) {
if (state == undefined)
return;
if (selector == undefined)
return state;
try {
return selector(state);
}
catch (error) {
return undefined;
}
} | javascript | function select(state, selector) {
if (state == undefined)
return;
if (selector == undefined)
return state;
try {
return selector(state);
}
catch (error) {
return undefined;
}
} | [
"function",
"select",
"(",
"state",
",",
"selector",
")",
"{",
"if",
"(",
"state",
"==",
"undefined",
")",
"return",
";",
"if",
"(",
"selector",
"==",
"undefined",
")",
"return",
"state",
";",
"try",
"{",
"return",
"selector",
"(",
"state",
")",
";",
... | Run selector function on the given state and return it's result. Return undefined if an error occurred
@param {*} state
@param {StateSelector} selector
@returns The value return by the selector, undefined if an error occurred. | [
"Run",
"selector",
"function",
"on",
"the",
"given",
"state",
"and",
"return",
"it",
"s",
"result",
".",
"Return",
"undefined",
"if",
"an",
"error",
"occurred"
] | 19d2a321587c67ee6ff406251ea3d6b3eeaa3418 | https://github.com/rintoj/statex/blob/19d2a321587c67ee6ff406251ea3d6b3eeaa3418/dist/core/state.js#L93-L104 |
32,914 | bholloway/nginject-loader | index.js | loader | function loader(content, sourceMap) {
/* jshint validthis:true */
// loader result is cacheable
this.cacheable();
// path of the file being processed
var filename = path.relative(this.options.context || process.cwd(), this.resourcePath).replace(/\\/g, '/'),
options = loaderUtils.parseQuery(this.query),
useMap = loader.sourceMap || options.sourceMap;
// make sure the AST has the data from the original source map
var pending = migrate.processSync(content, {
filename : filename,
sourceMap: useMap && (sourceMap || true),
quoteChar: options.singleQuote ? '\'' : '"'
});
// emit deprecation warning
if ((pending.isChanged) && (options.deprecate)) {
var text = ' ' + PACKAGE_NAME + ': @ngInject doctag is deprecated, use "ngInject" string directive instead';
this.emitWarning(text);
}
// emit errors
if (pending.errors.length) {
var text = pending.errors.map(indent).join('\n');
this.emitError(text);
}
// complete
if (useMap) {
this.callback(null, pending.content, pending.sourceMap);
} else {
return pending.content;
}
} | javascript | function loader(content, sourceMap) {
/* jshint validthis:true */
// loader result is cacheable
this.cacheable();
// path of the file being processed
var filename = path.relative(this.options.context || process.cwd(), this.resourcePath).replace(/\\/g, '/'),
options = loaderUtils.parseQuery(this.query),
useMap = loader.sourceMap || options.sourceMap;
// make sure the AST has the data from the original source map
var pending = migrate.processSync(content, {
filename : filename,
sourceMap: useMap && (sourceMap || true),
quoteChar: options.singleQuote ? '\'' : '"'
});
// emit deprecation warning
if ((pending.isChanged) && (options.deprecate)) {
var text = ' ' + PACKAGE_NAME + ': @ngInject doctag is deprecated, use "ngInject" string directive instead';
this.emitWarning(text);
}
// emit errors
if (pending.errors.length) {
var text = pending.errors.map(indent).join('\n');
this.emitError(text);
}
// complete
if (useMap) {
this.callback(null, pending.content, pending.sourceMap);
} else {
return pending.content;
}
} | [
"function",
"loader",
"(",
"content",
",",
"sourceMap",
")",
"{",
"/* jshint validthis:true */",
"// loader result is cacheable",
"this",
".",
"cacheable",
"(",
")",
";",
"// path of the file being processed",
"var",
"filename",
"=",
"path",
".",
"relative",
"(",
"thi... | Webpack loader where explicit @ngInject comment creates pre-minification $inject property.
@param {string} content JS content
@param {object} sourceMap The source-map
@returns {string|String} | [
"Webpack",
"loader",
"where",
"explicit"
] | 2ca938d453fb487c05fcca87f3b9c4ad8ae1ec7d | https://github.com/bholloway/nginject-loader/blob/2ca938d453fb487c05fcca87f3b9c4ad8ae1ec7d/index.js#L16-L52 |
32,915 | aurbano/smart-area | dist/smart-area.js | highlightText | function highlightText(){
var text = $scope.areaData,
html = htmlEncode(text);
if(typeof($scope.areaConfig.autocomplete) === 'undefined' || $scope.areaConfig.autocomplete.length === 0){
return;
}
$scope.areaConfig.autocomplete.forEach(function(autoList){
for(var i=0; i<autoList.words.length; i++){
if(typeof(autoList.words[i]) === "string"){
html = html.replace(new RegExp("([^\\w]|\\b)("+autoList.words[i]+")([^\\w]|\\b)", 'g'), '$1<span class="'+autoList.cssClass+'">$2</span>$3');
}else{
html = html.replace(autoList.words[i], function(match){
return '<span class="'+autoList.cssClass+'">'+match+'</span>';
});
}
}
});
// Add to the fakeArea
$scope.fakeArea = $sce.trustAsHtml(html);
} | javascript | function highlightText(){
var text = $scope.areaData,
html = htmlEncode(text);
if(typeof($scope.areaConfig.autocomplete) === 'undefined' || $scope.areaConfig.autocomplete.length === 0){
return;
}
$scope.areaConfig.autocomplete.forEach(function(autoList){
for(var i=0; i<autoList.words.length; i++){
if(typeof(autoList.words[i]) === "string"){
html = html.replace(new RegExp("([^\\w]|\\b)("+autoList.words[i]+")([^\\w]|\\b)", 'g'), '$1<span class="'+autoList.cssClass+'">$2</span>$3');
}else{
html = html.replace(autoList.words[i], function(match){
return '<span class="'+autoList.cssClass+'">'+match+'</span>';
});
}
}
});
// Add to the fakeArea
$scope.fakeArea = $sce.trustAsHtml(html);
} | [
"function",
"highlightText",
"(",
")",
"{",
"var",
"text",
"=",
"$scope",
".",
"areaData",
",",
"html",
"=",
"htmlEncode",
"(",
"text",
")",
";",
"if",
"(",
"typeof",
"(",
"$scope",
".",
"areaConfig",
".",
"autocomplete",
")",
"===",
"'undefined'",
"||",... | Perform the "syntax" highlighting of autocomplete words that have
a cssClass specified. | [
"Perform",
"the",
"syntax",
"highlighting",
"of",
"autocomplete",
"words",
"that",
"have",
"a",
"cssClass",
"specified",
"."
] | 372b17f9c4c5541591f181ddde4d0e4475c85f3f | https://github.com/aurbano/smart-area/blob/372b17f9c4c5541591f181ddde4d0e4475c85f3f/dist/smart-area.js#L301-L322 |
32,916 | aurbano/smart-area | dist/smart-area.js | triggerDropdownAutocomplete | function triggerDropdownAutocomplete(){
// First check with the autocomplete words (the ones that are not objects
var autocomplete = [],
suggestions = [],
text = $scope.areaData,
position = getCharacterPosition(),
lastWord = text.substr(0, position).split(/[\s\b{}]/);
// Get the last typed word
lastWord = lastWord[lastWord.length-1];
$scope.areaConfig.autocomplete.forEach(function(autoList){
autoList.words.forEach(function(word){
if(typeof(word) === 'string' && autocomplete.indexOf(word) < 0){
if(lastWord.length > 0 || lastWord.length < 1 && autoList.autocompleteOnSpace){
autocomplete.push(word);
}
}
});
});
if ($scope.areaConfig.dropdown !== undefined){
$scope.areaConfig.dropdown.forEach(function(element){
if(typeof(element.trigger) === 'string' && autocomplete.indexOf(element.trigger) < 0){
autocomplete.push(element.trigger);
}
});
}
// Now with the list, filter and return
autocomplete.forEach(function(word){
if(lastWord.length < word.length && word.toLowerCase().substr(0, lastWord.length) === lastWord.toLowerCase()){
suggestions.push({
display: $sce.trustAsHtml(word),
data: null
});
}
});
$scope.dropdown.customSelect = null;
$scope.dropdown.current = 0;
$scope.dropdown.content = suggestions;
} | javascript | function triggerDropdownAutocomplete(){
// First check with the autocomplete words (the ones that are not objects
var autocomplete = [],
suggestions = [],
text = $scope.areaData,
position = getCharacterPosition(),
lastWord = text.substr(0, position).split(/[\s\b{}]/);
// Get the last typed word
lastWord = lastWord[lastWord.length-1];
$scope.areaConfig.autocomplete.forEach(function(autoList){
autoList.words.forEach(function(word){
if(typeof(word) === 'string' && autocomplete.indexOf(word) < 0){
if(lastWord.length > 0 || lastWord.length < 1 && autoList.autocompleteOnSpace){
autocomplete.push(word);
}
}
});
});
if ($scope.areaConfig.dropdown !== undefined){
$scope.areaConfig.dropdown.forEach(function(element){
if(typeof(element.trigger) === 'string' && autocomplete.indexOf(element.trigger) < 0){
autocomplete.push(element.trigger);
}
});
}
// Now with the list, filter and return
autocomplete.forEach(function(word){
if(lastWord.length < word.length && word.toLowerCase().substr(0, lastWord.length) === lastWord.toLowerCase()){
suggestions.push({
display: $sce.trustAsHtml(word),
data: null
});
}
});
$scope.dropdown.customSelect = null;
$scope.dropdown.current = 0;
$scope.dropdown.content = suggestions;
} | [
"function",
"triggerDropdownAutocomplete",
"(",
")",
"{",
"// First check with the autocomplete words (the ones that are not objects",
"var",
"autocomplete",
"=",
"[",
"]",
",",
"suggestions",
"=",
"[",
"]",
",",
"text",
"=",
"$scope",
".",
"areaData",
",",
"position",
... | Trigger a simple autocomplete, this checks the last word and determines
whether any word on the autocomplete lists matches it | [
"Trigger",
"a",
"simple",
"autocomplete",
"this",
"checks",
"the",
"last",
"word",
"and",
"determines",
"whether",
"any",
"word",
"on",
"the",
"autocomplete",
"lists",
"matches",
"it"
] | 372b17f9c4c5541591f181ddde4d0e4475c85f3f | https://github.com/aurbano/smart-area/blob/372b17f9c4c5541591f181ddde4d0e4475c85f3f/dist/smart-area.js#L414-L456 |
32,917 | nufyoot/createsend-node | lib/interface/transactional.js | smartEmailDetails | function smartEmailDetails(details, callback) {
createsend.get('transactional/smartemail/'+details.smartEmailID, null, null, function(error, results) {
txResponseCallback(error, results, callback);
}, true);
} | javascript | function smartEmailDetails(details, callback) {
createsend.get('transactional/smartemail/'+details.smartEmailID, null, null, function(error, results) {
txResponseCallback(error, results, callback);
}, true);
} | [
"function",
"smartEmailDetails",
"(",
"details",
",",
"callback",
")",
"{",
"createsend",
".",
"get",
"(",
"'transactional/smartemail/'",
"+",
"details",
".",
"smartEmailID",
",",
"null",
",",
"null",
",",
"function",
"(",
"error",
",",
"results",
")",
"{",
... | Get the details for a smart transactional email | [
"Get",
"the",
"details",
"for",
"a",
"smart",
"transactional",
"email"
] | 13129f097968c8d15e607374b65969443963c8fc | https://github.com/nufyoot/createsend-node/blob/13129f097968c8d15e607374b65969443963c8fc/lib/interface/transactional.js#L28-L32 |
32,918 | nufyoot/createsend-node | lib/interface/transactional.js | sendSmartEmail | function sendSmartEmail(details, callback) {
createsend.post('transactional/smartemail/'+details.smartEmailID+'/send', null, details, function(error, results) {
txResponseCallback(error, results, callback);
}, true);
} | javascript | function sendSmartEmail(details, callback) {
createsend.post('transactional/smartemail/'+details.smartEmailID+'/send', null, details, function(error, results) {
txResponseCallback(error, results, callback);
}, true);
} | [
"function",
"sendSmartEmail",
"(",
"details",
",",
"callback",
")",
"{",
"createsend",
".",
"post",
"(",
"'transactional/smartemail/'",
"+",
"details",
".",
"smartEmailID",
"+",
"'/send'",
",",
"null",
",",
"details",
",",
"function",
"(",
"error",
",",
"resul... | Deliver a smart email. Properties in the data property will be available in your email as variables which can be referenced using our Template Language. | [
"Deliver",
"a",
"smart",
"email",
".",
"Properties",
"in",
"the",
"data",
"property",
"will",
"be",
"available",
"in",
"your",
"email",
"as",
"variables",
"which",
"can",
"be",
"referenced",
"using",
"our",
"Template",
"Language",
"."
] | 13129f097968c8d15e607374b65969443963c8fc | https://github.com/nufyoot/createsend-node/blob/13129f097968c8d15e607374b65969443963c8fc/lib/interface/transactional.js#L35-L39 |
32,919 | nufyoot/createsend-node | lib/interface/transactional.js | sendClassicEmail | function sendClassicEmail(details, callback) {
deleteNullProperties(details);
createsend.post('transactional/classicEmail/send', details.clientID, details, function(error, results) {
txResponseCallback(error, results, callback);
}, true);
} | javascript | function sendClassicEmail(details, callback) {
deleteNullProperties(details);
createsend.post('transactional/classicEmail/send', details.clientID, details, function(error, results) {
txResponseCallback(error, results, callback);
}, true);
} | [
"function",
"sendClassicEmail",
"(",
"details",
",",
"callback",
")",
"{",
"deleteNullProperties",
"(",
"details",
")",
";",
"createsend",
".",
"post",
"(",
"'transactional/classicEmail/send'",
",",
"details",
".",
"clientID",
",",
"details",
",",
"function",
"(",... | Send an email by providing your own content | [
"Send",
"an",
"email",
"by",
"providing",
"your",
"own",
"content"
] | 13129f097968c8d15e607374b65969443963c8fc | https://github.com/nufyoot/createsend-node/blob/13129f097968c8d15e607374b65969443963c8fc/lib/interface/transactional.js#L42-L47 |
32,920 | nufyoot/createsend-node | lib/interface/transactional.js | classicEmailGroupList | function classicEmailGroupList(details, callback) {
createsend.get('transactional/classicEmail/groups', details, null, function(error, results) {
txResponseCallback(error, results, callback);
}, true);
} | javascript | function classicEmailGroupList(details, callback) {
createsend.get('transactional/classicEmail/groups', details, null, function(error, results) {
txResponseCallback(error, results, callback);
}, true);
} | [
"function",
"classicEmailGroupList",
"(",
"details",
",",
"callback",
")",
"{",
"createsend",
".",
"get",
"(",
"'transactional/classicEmail/groups'",
",",
"details",
",",
"null",
",",
"function",
"(",
"error",
",",
"results",
")",
"{",
"txResponseCallback",
"(",
... | Get a list of classic email groups | [
"Get",
"a",
"list",
"of",
"classic",
"email",
"groups"
] | 13129f097968c8d15e607374b65969443963c8fc | https://github.com/nufyoot/createsend-node/blob/13129f097968c8d15e607374b65969443963c8fc/lib/interface/transactional.js#L50-L54 |
32,921 | nufyoot/createsend-node | lib/interface/transactional.js | statistics | function statistics(details, callback) {
deleteNullProperties(details);
createsend.get('transactional/statistics', details, null, function(error, results) {
txResponseCallback(error, results, callback);
}, true);
} | javascript | function statistics(details, callback) {
deleteNullProperties(details);
createsend.get('transactional/statistics', details, null, function(error, results) {
txResponseCallback(error, results, callback);
}, true);
} | [
"function",
"statistics",
"(",
"details",
",",
"callback",
")",
"{",
"deleteNullProperties",
"(",
"details",
")",
";",
"createsend",
".",
"get",
"(",
"'transactional/statistics'",
",",
"details",
",",
"null",
",",
"function",
"(",
"error",
",",
"results",
")",... | Get the delivery and engagement statistics, optionally filter by smart email or classic group. | [
"Get",
"the",
"delivery",
"and",
"engagement",
"statistics",
"optionally",
"filter",
"by",
"smart",
"email",
"or",
"classic",
"group",
"."
] | 13129f097968c8d15e607374b65969443963c8fc | https://github.com/nufyoot/createsend-node/blob/13129f097968c8d15e607374b65969443963c8fc/lib/interface/transactional.js#L57-L62 |
32,922 | nufyoot/createsend-node | lib/interface/transactional.js | messageDetails | function messageDetails(details, callback) {
createsend.get('transactional/messages/'+details.messageID, details, null, function(error, results) {
txResponseCallback(error, results, callback);
}, true);
} | javascript | function messageDetails(details, callback) {
createsend.get('transactional/messages/'+details.messageID, details, null, function(error, results) {
txResponseCallback(error, results, callback);
}, true);
} | [
"function",
"messageDetails",
"(",
"details",
",",
"callback",
")",
"{",
"createsend",
".",
"get",
"(",
"'transactional/messages/'",
"+",
"details",
".",
"messageID",
",",
"details",
",",
"null",
",",
"function",
"(",
"error",
",",
"results",
")",
"{",
"txRe... | Get the message details, no matter how it was sent. Includes status. | [
"Get",
"the",
"message",
"details",
"no",
"matter",
"how",
"it",
"was",
"sent",
".",
"Includes",
"status",
"."
] | 13129f097968c8d15e607374b65969443963c8fc | https://github.com/nufyoot/createsend-node/blob/13129f097968c8d15e607374b65969443963c8fc/lib/interface/transactional.js#L73-L77 |
32,923 | nufyoot/createsend-node | lib/interface/transactional.js | messageResend | function messageResend(details, callback) {
createsend.post('transactional/messages/'+details.messageID+'/resend', null, null, function(error, results) {
txResponseCallback(error, results, callback);
}, true);
} | javascript | function messageResend(details, callback) {
createsend.post('transactional/messages/'+details.messageID+'/resend', null, null, function(error, results) {
txResponseCallback(error, results, callback);
}, true);
} | [
"function",
"messageResend",
"(",
"details",
",",
"callback",
")",
"{",
"createsend",
".",
"post",
"(",
"'transactional/messages/'",
"+",
"details",
".",
"messageID",
"+",
"'/resend'",
",",
"null",
",",
"null",
",",
"function",
"(",
"error",
",",
"results",
... | Resend the message | [
"Resend",
"the",
"message"
] | 13129f097968c8d15e607374b65969443963c8fc | https://github.com/nufyoot/createsend-node/blob/13129f097968c8d15e607374b65969443963c8fc/lib/interface/transactional.js#L80-L84 |
32,924 | hipster-labs/angular-object-diff | angular-object-diff.js | diff | function diff(a, b, shallow, isOwn) {
if (a === b) {
return equalObj(a);
}
var diffValue = {};
var equal = true;
for (var key in a) {
if ((!isOwn && key in b) || (isOwn && typeof b != 'undefined' && b.hasOwnProperty(key))) {
if (a[key] === b[key]) {
diffValue[key] = equalObj(a[key]);
} else {
if (!shallow && isValidAttr(a[key], b[key])) {
var valueDiff = diff(a[key], b[key], shallow, isOwn);
if (valueDiff.changed == 'equal') {
diffValue[key] = equalObj(a[key]);
} else {
equal = false;
diffValue[key] = valueDiff;
}
} else {
equal = false;
diffValue[key] = {
changed: 'primitive change',
removed: a[key],
added: b[key]
}
}
}
} else {
equal = false;
diffValue[key] = {
changed: 'removed',
value: a[key]
}
}
}
for (key in b) {
if ((!isOwn && !(key in a)) || (isOwn && typeof a != 'undefined' && !a.hasOwnProperty(key))) {
equal = false;
diffValue[key] = {
changed: 'added',
value: b[key]
}
}
}
if (equal) {
return equalObj(a);
} else {
return {
changed: 'object change',
value: diffValue
}
}
} | javascript | function diff(a, b, shallow, isOwn) {
if (a === b) {
return equalObj(a);
}
var diffValue = {};
var equal = true;
for (var key in a) {
if ((!isOwn && key in b) || (isOwn && typeof b != 'undefined' && b.hasOwnProperty(key))) {
if (a[key] === b[key]) {
diffValue[key] = equalObj(a[key]);
} else {
if (!shallow && isValidAttr(a[key], b[key])) {
var valueDiff = diff(a[key], b[key], shallow, isOwn);
if (valueDiff.changed == 'equal') {
diffValue[key] = equalObj(a[key]);
} else {
equal = false;
diffValue[key] = valueDiff;
}
} else {
equal = false;
diffValue[key] = {
changed: 'primitive change',
removed: a[key],
added: b[key]
}
}
}
} else {
equal = false;
diffValue[key] = {
changed: 'removed',
value: a[key]
}
}
}
for (key in b) {
if ((!isOwn && !(key in a)) || (isOwn && typeof a != 'undefined' && !a.hasOwnProperty(key))) {
equal = false;
diffValue[key] = {
changed: 'added',
value: b[key]
}
}
}
if (equal) {
return equalObj(a);
} else {
return {
changed: 'object change',
value: diffValue
}
}
} | [
"function",
"diff",
"(",
"a",
",",
"b",
",",
"shallow",
",",
"isOwn",
")",
"{",
"if",
"(",
"a",
"===",
"b",
")",
"{",
"return",
"equalObj",
"(",
"a",
")",
";",
"}",
"var",
"diffValue",
"=",
"{",
"}",
";",
"var",
"equal",
"=",
"true",
";",
"fo... | diff between object a and b
@param {Object} a
@param {Object} b
@param shallow
@param isOwn
@return {Object} | [
"diff",
"between",
"object",
"a",
"and",
"b"
] | 4299d0680d2aa276ab52cc7e3654df8b2689c521 | https://github.com/hipster-labs/angular-object-diff/blob/4299d0680d2aa276ab52cc7e3654df8b2689c521/angular-object-diff.js#L58-L116 |
32,925 | taskcluster/gdb-js | src/index.js | escape | function escape (script) {
return script.replace(/\\/g, '\\\\').replace(/\n/g, '\\n')
.replace(/\r/g, '\\r').replace(/\t/g, '\\t').replace(/"/g, '\\"')
} | javascript | function escape (script) {
return script.replace(/\\/g, '\\\\').replace(/\n/g, '\\n')
.replace(/\r/g, '\\r').replace(/\t/g, '\\t').replace(/"/g, '\\"')
} | [
"function",
"escape",
"(",
"script",
")",
"{",
"return",
"script",
".",
"replace",
"(",
"/",
"\\\\",
"/",
"g",
",",
"'\\\\\\\\'",
")",
".",
"replace",
"(",
"/",
"\\n",
"/",
"g",
",",
"'\\\\n'",
")",
".",
"replace",
"(",
"/",
"\\r",
"/",
"g",
",",... | Escapes symbols in python code so that we can send it using inline mode.
@param {string} script The Python script.
@returns {string} The escaped python script.
@ignore | [
"Escapes",
"symbols",
"in",
"python",
"code",
"so",
"that",
"we",
"can",
"send",
"it",
"using",
"inline",
"mode",
"."
] | 497be0bb1e16866f4654e79a0a8da0ede396f031 | https://github.com/taskcluster/gdb-js/blob/497be0bb1e16866f4654e79a0a8da0ede396f031/src/index.js#L64-L67 |
32,926 | TodayTix/svg-sprite-webpack-plugin | src/plugin.js | replaceAll | function replaceAll(source, name, oldStr, newStr) {
const transformedSource = new ReplaceSource(source, name);
const reTester = new RegExp(oldStr, 'g');
let reResult = reTester.exec(source.source());
if (reResult == null) {
return source;
}
while (reResult != null) {
transformedSource.replace(
reResult.index,
reTester.lastIndex - 1,
newStr
);
reResult = reTester.exec(source.source());
}
return transformedSource;
} | javascript | function replaceAll(source, name, oldStr, newStr) {
const transformedSource = new ReplaceSource(source, name);
const reTester = new RegExp(oldStr, 'g');
let reResult = reTester.exec(source.source());
if (reResult == null) {
return source;
}
while (reResult != null) {
transformedSource.replace(
reResult.index,
reTester.lastIndex - 1,
newStr
);
reResult = reTester.exec(source.source());
}
return transformedSource;
} | [
"function",
"replaceAll",
"(",
"source",
",",
"name",
",",
"oldStr",
",",
"newStr",
")",
"{",
"const",
"transformedSource",
"=",
"new",
"ReplaceSource",
"(",
"source",
",",
"name",
")",
";",
"const",
"reTester",
"=",
"new",
"RegExp",
"(",
"oldStr",
",",
... | Takes a source, and a string to replace, and returns a ReplaceSource with
all the instances of that string replaced.
@param {Source} source The original source
@param {string} name ReplaceSource has a `name` param in its constructor.
I don't actually know why.
@param {string} oldStr The string to be replaced
@param {string} newStr The string to replace it with
@return {ReplaceSource} A Source object with all of the replacements applied | [
"Takes",
"a",
"source",
"and",
"a",
"string",
"to",
"replace",
"and",
"returns",
"a",
"ReplaceSource",
"with",
"all",
"the",
"instances",
"of",
"that",
"string",
"replaced",
"."
] | 941a0c5e01887d876f04b26feb5edae95f291080 | https://github.com/TodayTix/svg-sprite-webpack-plugin/blob/941a0c5e01887d876f04b26feb5edae95f291080/src/plugin.js#L18-L38 |
32,927 | bvaughn/jasmine-promise-matchers | source/source.js | function(promise, expectedState, opt_expectedData, opt_util, opt_customEqualityTesters) {
var info = {};
promise.then(
function(data) {
info.actualData = data;
info.actualState = PROMISE_STATE.RESOLVED;
},
function(data) {
info.actualData = data;
info.actualState = PROMISE_STATE.REJECTED;
});
$scope.$apply(); // Trigger Promise resolution
if (!info.actualState) {
// Trigger $httpBackend flush if any requests are pending
if ($httpBackend) {
try {
$httpBackend.flush();
} catch (err) {
if (err.message !== 'No pending request to flush !') {
throw err;
}
}
}
// Trigger $timeout flush if any deferred tasks are pending
if ($timeout) {
try {
$timeout.flush();
} catch (err) {
if (err.message !== 'No deferred tasks to be flushed') {
throw err;
}
}
}
// Trigger $interval flush if any deferred tasks are pending
if ($interval) {
try {
// Flushing $interval requires an amount of time, I believe this number should flush pretty much anything useful...
$interval.flush(100000);
} catch (err) {
if (err.message !== 'No deferred tasks to be flushed') {
throw err;
}
}
}
}
info.message = 'Expected ' + info.actualState + ' to be ' + expectedState;
info.pass = info.actualState === expectedState;
// If resolve/reject expectations have been made, check the data..
if (opt_expectedData !== undefined && info.pass) {
// Jasmine 2
if (opt_util) {
// Detect Jasmine's asymmetric equality matchers and use Jasmine's own equality test for them
// Otherwise use Angular's equality check since it ignores properties that are functions
if (opt_expectedData && opt_expectedData.asymmetricMatch) {
info.pass = opt_util.equals(info.actualData, opt_expectedData, opt_customEqualityTesters);
} else {
info.pass = angular.equals(info.actualData, opt_expectedData);
}
// Jasmine 1.3
} else {
if (opt_expectedData instanceof jasmine.Matchers.Any ||
opt_expectedData instanceof jasmine.Matchers.ObjectContaining) {
info.pass = opt_expectedData.jasmineMatches(info.actualData);
} else {
info.pass = angular.equals(info.actualData, opt_expectedData);
}
}
var actual = jasmine.pp(info.actualData);
var expected = jasmine.pp(opt_expectedData);
info.message = 'Expected ' + actual + ' to be ' + expected;
}
return info;
} | javascript | function(promise, expectedState, opt_expectedData, opt_util, opt_customEqualityTesters) {
var info = {};
promise.then(
function(data) {
info.actualData = data;
info.actualState = PROMISE_STATE.RESOLVED;
},
function(data) {
info.actualData = data;
info.actualState = PROMISE_STATE.REJECTED;
});
$scope.$apply(); // Trigger Promise resolution
if (!info.actualState) {
// Trigger $httpBackend flush if any requests are pending
if ($httpBackend) {
try {
$httpBackend.flush();
} catch (err) {
if (err.message !== 'No pending request to flush !') {
throw err;
}
}
}
// Trigger $timeout flush if any deferred tasks are pending
if ($timeout) {
try {
$timeout.flush();
} catch (err) {
if (err.message !== 'No deferred tasks to be flushed') {
throw err;
}
}
}
// Trigger $interval flush if any deferred tasks are pending
if ($interval) {
try {
// Flushing $interval requires an amount of time, I believe this number should flush pretty much anything useful...
$interval.flush(100000);
} catch (err) {
if (err.message !== 'No deferred tasks to be flushed') {
throw err;
}
}
}
}
info.message = 'Expected ' + info.actualState + ' to be ' + expectedState;
info.pass = info.actualState === expectedState;
// If resolve/reject expectations have been made, check the data..
if (opt_expectedData !== undefined && info.pass) {
// Jasmine 2
if (opt_util) {
// Detect Jasmine's asymmetric equality matchers and use Jasmine's own equality test for them
// Otherwise use Angular's equality check since it ignores properties that are functions
if (opt_expectedData && opt_expectedData.asymmetricMatch) {
info.pass = opt_util.equals(info.actualData, opt_expectedData, opt_customEqualityTesters);
} else {
info.pass = angular.equals(info.actualData, opt_expectedData);
}
// Jasmine 1.3
} else {
if (opt_expectedData instanceof jasmine.Matchers.Any ||
opt_expectedData instanceof jasmine.Matchers.ObjectContaining) {
info.pass = opt_expectedData.jasmineMatches(info.actualData);
} else {
info.pass = angular.equals(info.actualData, opt_expectedData);
}
}
var actual = jasmine.pp(info.actualData);
var expected = jasmine.pp(opt_expectedData);
info.message = 'Expected ' + actual + ' to be ' + expected;
}
return info;
} | [
"function",
"(",
"promise",
",",
"expectedState",
",",
"opt_expectedData",
",",
"opt_util",
",",
"opt_customEqualityTesters",
")",
"{",
"var",
"info",
"=",
"{",
"}",
";",
"promise",
".",
"then",
"(",
"function",
"(",
"data",
")",
"{",
"info",
".",
"actualD... | Helper method to verify expectations and return a Jasmine-friendly info-object.
The last 2 parameters are optional and only required for Jasmine 2.
For more info see http://jasmine.github.io/2.0/custom_matcher.html
@param promise Promise to test
@param expectedState PROMISE_STATE enum
@param opt_expectedData Optional value promise was expected to reject/resolve with
@param opt_util Jasmine 2 utility providing its own equality method
@param opt_customEqualityTesters Required by opt_util equality method | [
"Helper",
"method",
"to",
"verify",
"expectations",
"and",
"return",
"a",
"Jasmine",
"-",
"friendly",
"info",
"-",
"object",
"."
] | 9214777863fd42e2292ba025ea0ffb3802a6ff21 | https://github.com/bvaughn/jasmine-promise-matchers/blob/9214777863fd42e2292ba025ea0ffb3802a6ff21/source/source.js#L44-L128 | |
32,928 | taion/rrtr | modules/createTransitionManager.js | listenBeforeLeavingRoute | function listenBeforeLeavingRoute(route, hook) {
// TODO: Warn if they register for a route that isn't currently
// active. They're probably doing something wrong, like re-creating
// route objects on every location change.
const routeID = getRouteID(route)
let hooks = RouteHooks[routeID]
if (!hooks) {
let thereWereNoRouteHooks = !hasAnyProperties(RouteHooks)
RouteHooks[routeID] = [ hook ]
if (thereWereNoRouteHooks) {
// setup transition & beforeunload hooks
unlistenBefore = history.listenBefore(transitionHook)
if (history.listenBeforeUnload)
unlistenBeforeUnload = history.listenBeforeUnload(beforeUnloadHook)
}
} else {
if (hooks.indexOf(hook) === -1) {
warning(
false,
'adding multiple leave hooks for the same route is deprecated; manage multiple confirmations in your own code instead'
)
hooks.push(hook)
}
}
return function () {
const hooks = RouteHooks[routeID]
if (hooks) {
const newHooks = hooks.filter(item => item !== hook)
if (newHooks.length === 0) {
removeListenBeforeHooksForRoute(route)
} else {
RouteHooks[routeID] = newHooks
}
}
}
} | javascript | function listenBeforeLeavingRoute(route, hook) {
// TODO: Warn if they register for a route that isn't currently
// active. They're probably doing something wrong, like re-creating
// route objects on every location change.
const routeID = getRouteID(route)
let hooks = RouteHooks[routeID]
if (!hooks) {
let thereWereNoRouteHooks = !hasAnyProperties(RouteHooks)
RouteHooks[routeID] = [ hook ]
if (thereWereNoRouteHooks) {
// setup transition & beforeunload hooks
unlistenBefore = history.listenBefore(transitionHook)
if (history.listenBeforeUnload)
unlistenBeforeUnload = history.listenBeforeUnload(beforeUnloadHook)
}
} else {
if (hooks.indexOf(hook) === -1) {
warning(
false,
'adding multiple leave hooks for the same route is deprecated; manage multiple confirmations in your own code instead'
)
hooks.push(hook)
}
}
return function () {
const hooks = RouteHooks[routeID]
if (hooks) {
const newHooks = hooks.filter(item => item !== hook)
if (newHooks.length === 0) {
removeListenBeforeHooksForRoute(route)
} else {
RouteHooks[routeID] = newHooks
}
}
}
} | [
"function",
"listenBeforeLeavingRoute",
"(",
"route",
",",
"hook",
")",
"{",
"// TODO: Warn if they register for a route that isn't currently",
"// active. They're probably doing something wrong, like re-creating",
"// route objects on every location change.",
"const",
"routeID",
"=",
"g... | Registers the given hook function to run before leaving the given route.
During a normal transition, the hook function receives the next location
as its only argument and must return either a) a prompt message to show
the user, to make sure they want to leave the page or b) false, to prevent
the transition.
During the beforeunload event (in browsers) the hook receives no arguments.
In this case it must return a prompt message to prevent the transition.
Returns a function that may be used to unbind the listener. | [
"Registers",
"the",
"given",
"hook",
"function",
"to",
"run",
"before",
"leaving",
"the",
"given",
"route",
"."
] | a8c86d059daffad47ca893d98e9b6049d49eb83c | https://github.com/taion/rrtr/blob/a8c86d059daffad47ca893d98e9b6049d49eb83c/modules/createTransitionManager.js#L210-L253 |
32,929 | taion/rrtr | modules/createTransitionManager.js | listen | function listen(listener) {
// TODO: Only use a single history listener. Otherwise we'll
// end up with multiple concurrent calls to match.
return history.listen(function (location) {
if (state.location === location) {
listener(null, state)
} else {
match(location, function (error, redirectLocation, nextState) {
if (error) {
listener(error)
} else if (redirectLocation) {
history.transitionTo(redirectLocation)
} else if (nextState) {
listener(null, nextState)
} else {
warning(
false,
'Location "%s" did not match any routes',
location.pathname + location.search + location.hash
)
}
})
}
})
} | javascript | function listen(listener) {
// TODO: Only use a single history listener. Otherwise we'll
// end up with multiple concurrent calls to match.
return history.listen(function (location) {
if (state.location === location) {
listener(null, state)
} else {
match(location, function (error, redirectLocation, nextState) {
if (error) {
listener(error)
} else if (redirectLocation) {
history.transitionTo(redirectLocation)
} else if (nextState) {
listener(null, nextState)
} else {
warning(
false,
'Location "%s" did not match any routes',
location.pathname + location.search + location.hash
)
}
})
}
})
} | [
"function",
"listen",
"(",
"listener",
")",
"{",
"// TODO: Only use a single history listener. Otherwise we'll",
"// end up with multiple concurrent calls to match.",
"return",
"history",
".",
"listen",
"(",
"function",
"(",
"location",
")",
"{",
"if",
"(",
"state",
".",
... | This is the API for stateful environments. As the location
changes, we update state and call the listener. We can also
gracefully handle errors and redirects. | [
"This",
"is",
"the",
"API",
"for",
"stateful",
"environments",
".",
"As",
"the",
"location",
"changes",
"we",
"update",
"state",
"and",
"call",
"the",
"listener",
".",
"We",
"can",
"also",
"gracefully",
"handle",
"errors",
"and",
"redirects",
"."
] | a8c86d059daffad47ca893d98e9b6049d49eb83c | https://github.com/taion/rrtr/blob/a8c86d059daffad47ca893d98e9b6049d49eb83c/modules/createTransitionManager.js#L260-L284 |
32,930 | gleero/grunt-favicons | tasks/favicons.js | function(args) {
args.unshift("convert");
var ret = execute(args.join(" "));
if (ret.code === 127) {
return grunt.warn(
'You need to have ImageMagick installed in your PATH for this task to work.'
);
}
} | javascript | function(args) {
args.unshift("convert");
var ret = execute(args.join(" "));
if (ret.code === 127) {
return grunt.warn(
'You need to have ImageMagick installed in your PATH for this task to work.'
);
}
} | [
"function",
"(",
"args",
")",
"{",
"args",
".",
"unshift",
"(",
"\"convert\"",
")",
";",
"var",
"ret",
"=",
"execute",
"(",
"args",
".",
"join",
"(",
"\" \"",
")",
")",
";",
"if",
"(",
"ret",
".",
"code",
"===",
"127",
")",
"{",
"return",
"grunt"... | Convert image with imagemagick | [
"Convert",
"image",
"with",
"imagemagick"
] | 99489fce4a0866f321e620534727c9e306c2605d | https://github.com/gleero/grunt-favicons/blob/99489fce4a0866f321e620534727c9e306c2605d/tasks/favicons.js#L58-L66 | |
32,931 | thinkjs/think-model | index.js | injectModel | function injectModel(name, config, m) {
const modelConfig = app.think.config('model', undefined, m);
const cacheConfig = app.think.config('cache', undefined, m);
config = helper.parseAdapterConfig(modelConfig, config);
const instance = model(name, config, m);
instance._cacheConfig = cacheConfig;
return instance;
} | javascript | function injectModel(name, config, m) {
const modelConfig = app.think.config('model', undefined, m);
const cacheConfig = app.think.config('cache', undefined, m);
config = helper.parseAdapterConfig(modelConfig, config);
const instance = model(name, config, m);
instance._cacheConfig = cacheConfig;
return instance;
} | [
"function",
"injectModel",
"(",
"name",
",",
"config",
",",
"m",
")",
"{",
"const",
"modelConfig",
"=",
"app",
".",
"think",
".",
"config",
"(",
"'model'",
",",
"undefined",
",",
"m",
")",
";",
"const",
"cacheConfig",
"=",
"app",
".",
"think",
".",
"... | inject model method
@param {String} name
@param {Object} config
@param {String} m | [
"inject",
"model",
"method"
] | 539f74fb54313ceaf20befe4fc8bb206b93cfadc | https://github.com/thinkjs/think-model/blob/539f74fb54313ceaf20befe4fc8bb206b93cfadc/index.js#L42-L49 |
32,932 | RangerMauve/mqtt-regex | index.js | parse | function parse(topic) {
var tokens = tokenize(topic).map(process_token);
var result = {
regex: make_regex(tokens),
getParams: make_pram_getter(tokens),
topic: make_clean_topic(tokens)
};
result.exec = exec.bind(result);
return result;
} | javascript | function parse(topic) {
var tokens = tokenize(topic).map(process_token);
var result = {
regex: make_regex(tokens),
getParams: make_pram_getter(tokens),
topic: make_clean_topic(tokens)
};
result.exec = exec.bind(result);
return result;
} | [
"function",
"parse",
"(",
"topic",
")",
"{",
"var",
"tokens",
"=",
"tokenize",
"(",
"topic",
")",
".",
"map",
"(",
"process_token",
")",
";",
"var",
"result",
"=",
"{",
"regex",
":",
"make_regex",
"(",
"tokens",
")",
",",
"getParams",
":",
"make_pram_g... | Parses topic string with parameters
@param topic Topic string with optional params
@returns {Object} Compiles a regex for matching topics, getParams for getting params, and exec for doing both | [
"Parses",
"topic",
"string",
"with",
"parameters"
] | a9e901df546763117f8d73f5add874bf91f9e995 | https://github.com/RangerMauve/mqtt-regex/blob/a9e901df546763117f8d73f5add874bf91f9e995/index.js#L34-L43 |
32,933 | RangerMauve/mqtt-regex | index.js | exec | function exec(topic) {
var regex = this.regex;
var getParams = this.getParams;
var match = regex.exec(topic);
if (match) return getParams(match);
} | javascript | function exec(topic) {
var regex = this.regex;
var getParams = this.getParams;
var match = regex.exec(topic);
if (match) return getParams(match);
} | [
"function",
"exec",
"(",
"topic",
")",
"{",
"var",
"regex",
"=",
"this",
".",
"regex",
";",
"var",
"getParams",
"=",
"this",
".",
"getParams",
";",
"var",
"match",
"=",
"regex",
".",
"exec",
"(",
"topic",
")",
";",
"if",
"(",
"match",
")",
"return"... | Matches regex against topic, returns params if successful
@param topic Topic to match | [
"Matches",
"regex",
"against",
"topic",
"returns",
"params",
"if",
"successful"
] | a9e901df546763117f8d73f5add874bf91f9e995 | https://github.com/RangerMauve/mqtt-regex/blob/a9e901df546763117f8d73f5add874bf91f9e995/index.js#L49-L54 |
32,934 | RangerMauve/mqtt-regex | index.js | process_token | function process_token(token, index, tokens) {
var last = (index === (tokens.length - 1));
if (token[0] === "+") return process_single(token, last);
else if (token[0] === "#") return process_multi(token, last);
else return process_raw(token, last);
} | javascript | function process_token(token, index, tokens) {
var last = (index === (tokens.length - 1));
if (token[0] === "+") return process_single(token, last);
else if (token[0] === "#") return process_multi(token, last);
else return process_raw(token, last);
} | [
"function",
"process_token",
"(",
"token",
",",
"index",
",",
"tokens",
")",
"{",
"var",
"last",
"=",
"(",
"index",
"===",
"(",
"tokens",
".",
"length",
"-",
"1",
")",
")",
";",
"if",
"(",
"token",
"[",
"0",
"]",
"===",
"\"+\"",
")",
"return",
"p... | Processes token and determines if it's a `single`, `multi` or `raw` token Each token contains the type, an optional parameter name, and a piece of the regex The piece can have a different syntax for when it is last | [
"Processes",
"token",
"and",
"determines",
"if",
"it",
"s",
"a",
"single",
"multi",
"or",
"raw",
"token",
"Each",
"token",
"contains",
"the",
"type",
"an",
"optional",
"parameter",
"name",
"and",
"a",
"piece",
"of",
"the",
"regex",
"The",
"piece",
"can",
... | a9e901df546763117f8d73f5add874bf91f9e995 | https://github.com/RangerMauve/mqtt-regex/blob/a9e901df546763117f8d73f5add874bf91f9e995/index.js#L64-L69 |
32,935 | RangerMauve/mqtt-regex | index.js | process_raw | function process_raw(token) {
var token = escapeRegex(token);
return {
type: "raw",
piece: token + "/",
last: token + "/?"
};
} | javascript | function process_raw(token) {
var token = escapeRegex(token);
return {
type: "raw",
piece: token + "/",
last: token + "/?"
};
} | [
"function",
"process_raw",
"(",
"token",
")",
"{",
"var",
"token",
"=",
"escapeRegex",
"(",
"token",
")",
";",
"return",
"{",
"type",
":",
"\"raw\"",
",",
"piece",
":",
"token",
"+",
"\"/\"",
",",
"last",
":",
"token",
"+",
"\"/?\"",
"}",
";",
"}"
] | Processes a raw string for the path, no special logic is expected | [
"Processes",
"a",
"raw",
"string",
"for",
"the",
"path",
"no",
"special",
"logic",
"is",
"expected"
] | a9e901df546763117f8d73f5add874bf91f9e995 | https://github.com/RangerMauve/mqtt-regex/blob/a9e901df546763117f8d73f5add874bf91f9e995/index.js#L95-L102 |
32,936 | RangerMauve/mqtt-regex | index.js | make_clean_topic | function make_clean_topic(tokens) {
return tokens.map(function (token) {
if (token.type === "raw") return token.piece.slice(0, -1);
else if (token.type === "single") return "+";
else if (token.type === "multi") return "#";
else return ""; // Wat
}).join("/");
} | javascript | function make_clean_topic(tokens) {
return tokens.map(function (token) {
if (token.type === "raw") return token.piece.slice(0, -1);
else if (token.type === "single") return "+";
else if (token.type === "multi") return "#";
else return ""; // Wat
}).join("/");
} | [
"function",
"make_clean_topic",
"(",
"tokens",
")",
"{",
"return",
"tokens",
".",
"map",
"(",
"function",
"(",
"token",
")",
"{",
"if",
"(",
"token",
".",
"type",
"===",
"\"raw\"",
")",
"return",
"token",
".",
"piece",
".",
"slice",
"(",
"0",
",",
"-... | Turn a topic pattern into a regular MQTT topic | [
"Turn",
"a",
"topic",
"pattern",
"into",
"a",
"regular",
"MQTT",
"topic"
] | a9e901df546763117f8d73f5add874bf91f9e995 | https://github.com/RangerMauve/mqtt-regex/blob/a9e901df546763117f8d73f5add874bf91f9e995/index.js#L105-L112 |
32,937 | RangerMauve/mqtt-regex | index.js | make_regex | function make_regex(tokens) {
var str = tokens.reduce(function (res, token, index) {
var is_last = (index == (tokens.length - 1));
var before_multi = (index === (tokens.length - 2)) && (last(tokens).type == "multi");
return res + ((is_last || before_multi) ? token.last : token.piece);
},
"");
return new RegExp("^" + str + "$");
} | javascript | function make_regex(tokens) {
var str = tokens.reduce(function (res, token, index) {
var is_last = (index == (tokens.length - 1));
var before_multi = (index === (tokens.length - 2)) && (last(tokens).type == "multi");
return res + ((is_last || before_multi) ? token.last : token.piece);
},
"");
return new RegExp("^" + str + "$");
} | [
"function",
"make_regex",
"(",
"tokens",
")",
"{",
"var",
"str",
"=",
"tokens",
".",
"reduce",
"(",
"function",
"(",
"res",
",",
"token",
",",
"index",
")",
"{",
"var",
"is_last",
"=",
"(",
"index",
"==",
"(",
"tokens",
".",
"length",
"-",
"1",
")"... | Generates the RegExp object from the tokens | [
"Generates",
"the",
"RegExp",
"object",
"from",
"the",
"tokens"
] | a9e901df546763117f8d73f5add874bf91f9e995 | https://github.com/RangerMauve/mqtt-regex/blob/a9e901df546763117f8d73f5add874bf91f9e995/index.js#L115-L123 |
32,938 | RangerMauve/mqtt-regex | index.js | make_pram_getter | function make_pram_getter(tokens) {
return function (results) {
// Get only the capturing tokens
var capture_tokens = remove_raw(tokens);
var res = {};
// If the regex didn't actually match, just return an empty object
if (!results) return res;
// Remove the first item and iterate through the capture groups
results.slice(1).forEach(function (capture, index) {
// Retreive the token description for the capture group
var token = capture_tokens[index];
var param = capture;
// If the token doesn't have a name, continue to next group
if (!token.name) return;
// If the token is `multi`, split the capture along `/`, remove empty items
if (token.type === "multi") {
param = capture.split("/");
if (!last(param))
param = remove_last(param);
// Otherwise, remove any trailing `/`
} else if (last(capture) === "/")
param = remove_last(capture);
// Set the param on the result object
res[token.name] = param;
});
return res;
}
} | javascript | function make_pram_getter(tokens) {
return function (results) {
// Get only the capturing tokens
var capture_tokens = remove_raw(tokens);
var res = {};
// If the regex didn't actually match, just return an empty object
if (!results) return res;
// Remove the first item and iterate through the capture groups
results.slice(1).forEach(function (capture, index) {
// Retreive the token description for the capture group
var token = capture_tokens[index];
var param = capture;
// If the token doesn't have a name, continue to next group
if (!token.name) return;
// If the token is `multi`, split the capture along `/`, remove empty items
if (token.type === "multi") {
param = capture.split("/");
if (!last(param))
param = remove_last(param);
// Otherwise, remove any trailing `/`
} else if (last(capture) === "/")
param = remove_last(capture);
// Set the param on the result object
res[token.name] = param;
});
return res;
}
} | [
"function",
"make_pram_getter",
"(",
"tokens",
")",
"{",
"return",
"function",
"(",
"results",
")",
"{",
"// Get only the capturing tokens",
"var",
"capture_tokens",
"=",
"remove_raw",
"(",
"tokens",
")",
";",
"var",
"res",
"=",
"{",
"}",
";",
"// If the regex d... | Generates the function for getting the params object from the regex results | [
"Generates",
"the",
"function",
"for",
"getting",
"the",
"params",
"object",
"from",
"the",
"regex",
"results"
] | a9e901df546763117f8d73f5add874bf91f9e995 | https://github.com/RangerMauve/mqtt-regex/blob/a9e901df546763117f8d73f5add874bf91f9e995/index.js#L126-L156 |
32,939 | jmjuanes/electron-ejs | index.js | function () {
//Render the full file
return ejs.renderFile(file, data, options, function (error, content) {
if (error) {
self.emit("error", error);
return callback(-2);
}
//Call the provided callback with the file content
return callback({
"data": new Buffer(content),
"mimeType": "text/html"
});
});
} | javascript | function () {
//Render the full file
return ejs.renderFile(file, data, options, function (error, content) {
if (error) {
self.emit("error", error);
return callback(-2);
}
//Call the provided callback with the file content
return callback({
"data": new Buffer(content),
"mimeType": "text/html"
});
});
} | [
"function",
"(",
")",
"{",
"//Render the full file",
"return",
"ejs",
".",
"renderFile",
"(",
"file",
",",
"data",
",",
"options",
",",
"function",
"(",
"error",
",",
"content",
")",
"{",
"if",
"(",
"error",
")",
"{",
"self",
".",
"emit",
"(",
"\"error... | Render template function | [
"Render",
"template",
"function"
] | dc1ad4c5b43314f6e59edc63c34233930dc83401 | https://github.com/jmjuanes/electron-ejs/blob/dc1ad4c5b43314f6e59edc63c34233930dc83401/index.js#L57-L70 | |
32,940 | jmjuanes/electron-ejs | index.js | ParsePath | function ParsePath(u) {
//Parse the url
let p = url.parse(u);
//Get the path name
let pname = p.pathname;
//Check for Windows
if( process.platform === "win32") {
//Remove the first / from the path
//https://github.com/jmjuanes/electron-ejs/pull/4#issuecomment-219254028
pname = pname.substr(1);
}
//Sanitize URL. Spaces turn into `%20` symbols in the path and
//throws a `File Not Found Event`. This fix allows folder paths to have
//spaces in the folder name.
//https://github.com/jmjuanes/electron-ejs/pull/9
return pname.replace(/\s/g, " ").replace(/%20/g, " ");
} | javascript | function ParsePath(u) {
//Parse the url
let p = url.parse(u);
//Get the path name
let pname = p.pathname;
//Check for Windows
if( process.platform === "win32") {
//Remove the first / from the path
//https://github.com/jmjuanes/electron-ejs/pull/4#issuecomment-219254028
pname = pname.substr(1);
}
//Sanitize URL. Spaces turn into `%20` symbols in the path and
//throws a `File Not Found Event`. This fix allows folder paths to have
//spaces in the folder name.
//https://github.com/jmjuanes/electron-ejs/pull/9
return pname.replace(/\s/g, " ").replace(/%20/g, " ");
} | [
"function",
"ParsePath",
"(",
"u",
")",
"{",
"//Parse the url",
"let",
"p",
"=",
"url",
".",
"parse",
"(",
"u",
")",
";",
"//Get the path name",
"let",
"pname",
"=",
"p",
".",
"pathname",
";",
"//Check for Windows",
"if",
"(",
"process",
".",
"platform",
... | Function to parse the path | [
"Function",
"to",
"parse",
"the",
"path"
] | dc1ad4c5b43314f6e59edc63c34233930dc83401 | https://github.com/jmjuanes/electron-ejs/blob/dc1ad4c5b43314f6e59edc63c34233930dc83401/index.js#L97-L113 |
32,941 | BorisChumichev/everpolate | lib/linearRegression.js | linearRegression | function linearRegression(functionValuesX, functionValuesY){
var regression = {}
, x = functionValuesX
, y = functionValuesY
, n = y.length
, sum_x = 0
, sum_y = 0
, sum_xy = 0
, sum_xx = 0
, sum_yy = 0
for (var i = 0; i < y.length; i++) {
sum_x += x[i]
sum_y += y[i]
sum_xy += (x[i]*y[i])
sum_xx += (x[i]*x[i])
sum_yy += (y[i]*y[i])
}
regression.slope = (n * sum_xy - sum_x * sum_y) / (n*sum_xx - sum_x * sum_x)
regression.intercept = (sum_y - regression.slope * sum_x)/n
regression.rSquared = Math.pow((n*sum_xy - sum_x*sum_y)/Math.sqrt((n*sum_xx-sum_x*sum_x)*(n*sum_yy-sum_y*sum_y)),2)
regression.evaluate = function (pointsToEvaluate) {
var x = help.makeItArrayIfItsNot(pointsToEvaluate)
, result = []
, that = this
x.forEach(function (point) {
result.push(that.slope*point + that.intercept)
})
return result
}
return regression
} | javascript | function linearRegression(functionValuesX, functionValuesY){
var regression = {}
, x = functionValuesX
, y = functionValuesY
, n = y.length
, sum_x = 0
, sum_y = 0
, sum_xy = 0
, sum_xx = 0
, sum_yy = 0
for (var i = 0; i < y.length; i++) {
sum_x += x[i]
sum_y += y[i]
sum_xy += (x[i]*y[i])
sum_xx += (x[i]*x[i])
sum_yy += (y[i]*y[i])
}
regression.slope = (n * sum_xy - sum_x * sum_y) / (n*sum_xx - sum_x * sum_x)
regression.intercept = (sum_y - regression.slope * sum_x)/n
regression.rSquared = Math.pow((n*sum_xy - sum_x*sum_y)/Math.sqrt((n*sum_xx-sum_x*sum_x)*(n*sum_yy-sum_y*sum_y)),2)
regression.evaluate = function (pointsToEvaluate) {
var x = help.makeItArrayIfItsNot(pointsToEvaluate)
, result = []
, that = this
x.forEach(function (point) {
result.push(that.slope*point + that.intercept)
})
return result
}
return regression
} | [
"function",
"linearRegression",
"(",
"functionValuesX",
",",
"functionValuesY",
")",
"{",
"var",
"regression",
"=",
"{",
"}",
",",
"x",
"=",
"functionValuesX",
",",
"y",
"=",
"functionValuesY",
",",
"n",
"=",
"y",
".",
"length",
",",
"sum_x",
"=",
"0",
"... | Computes Linear Regression slope, intercept, r-squared and returns
a function which can be used for evaluating linear regression
at a particular x-value
@param functionValuesX {Array}
@param functionValuesY {Array}
@returns {Object} | [
"Computes",
"Linear",
"Regression",
"slope",
"intercept",
"r",
"-",
"squared",
"and",
"returns",
"a",
"function",
"which",
"can",
"be",
"used",
"for",
"evaluating",
"linear",
"regression",
"at",
"a",
"particular",
"x",
"-",
"value"
] | 00201c964891d37e8cfa6922057c5069db4a37d4 | https://github.com/BorisChumichev/everpolate/blob/00201c964891d37e8cfa6922057c5069db4a37d4/lib/linearRegression.js#L17-L50 |
32,942 | Rob--W/proxy-from-env | index.js | shouldProxy | function shouldProxy(hostname, port) {
var NO_PROXY = getEnv('no_proxy').toLowerCase();
if (!NO_PROXY) {
return true; // Always proxy if NO_PROXY is not set.
}
if (NO_PROXY === '*') {
return false; // Never proxy if wildcard is set.
}
return NO_PROXY.split(/[,\s]/).every(function(proxy) {
if (!proxy) {
return true; // Skip zero-length hosts.
}
var parsedProxy = proxy.match(/^(.+):(\d+)$/);
var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy;
var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0;
if (parsedProxyPort && parsedProxyPort !== port) {
return true; // Skip if ports don't match.
}
if (!/^[.*]/.test(parsedProxyHostname)) {
// No wildcards, so stop proxying if there is an exact match.
return hostname !== parsedProxyHostname;
}
if (parsedProxyHostname.charAt(0) === '*') {
// Remove leading wildcard.
parsedProxyHostname = parsedProxyHostname.slice(1);
}
// Stop proxying if the hostname ends with the no_proxy host.
return !stringEndsWith.call(hostname, parsedProxyHostname);
});
} | javascript | function shouldProxy(hostname, port) {
var NO_PROXY = getEnv('no_proxy').toLowerCase();
if (!NO_PROXY) {
return true; // Always proxy if NO_PROXY is not set.
}
if (NO_PROXY === '*') {
return false; // Never proxy if wildcard is set.
}
return NO_PROXY.split(/[,\s]/).every(function(proxy) {
if (!proxy) {
return true; // Skip zero-length hosts.
}
var parsedProxy = proxy.match(/^(.+):(\d+)$/);
var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy;
var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0;
if (parsedProxyPort && parsedProxyPort !== port) {
return true; // Skip if ports don't match.
}
if (!/^[.*]/.test(parsedProxyHostname)) {
// No wildcards, so stop proxying if there is an exact match.
return hostname !== parsedProxyHostname;
}
if (parsedProxyHostname.charAt(0) === '*') {
// Remove leading wildcard.
parsedProxyHostname = parsedProxyHostname.slice(1);
}
// Stop proxying if the hostname ends with the no_proxy host.
return !stringEndsWith.call(hostname, parsedProxyHostname);
});
} | [
"function",
"shouldProxy",
"(",
"hostname",
",",
"port",
")",
"{",
"var",
"NO_PROXY",
"=",
"getEnv",
"(",
"'no_proxy'",
")",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"!",
"NO_PROXY",
")",
"{",
"return",
"true",
";",
"// Always proxy if NO_PROXY is not s... | Determines whether a given URL should be proxied.
@param {string} hostname - The host name of the URL.
@param {number} port - The effective port of the URL.
@returns {boolean} Whether the given URL should be proxied.
@private | [
"Determines",
"whether",
"a",
"given",
"URL",
"should",
"be",
"proxied",
"."
] | e0d07a9350568b3a0c3bb28dafd3766206961a02 | https://github.com/Rob--W/proxy-from-env/blob/e0d07a9350568b3a0c3bb28dafd3766206961a02/index.js#L58-L90 |
32,943 | Rob--W/proxy-from-env | index.js | getEnv | function getEnv(key) {
return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || '';
} | javascript | function getEnv(key) {
return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || '';
} | [
"function",
"getEnv",
"(",
"key",
")",
"{",
"return",
"process",
".",
"env",
"[",
"key",
".",
"toLowerCase",
"(",
")",
"]",
"||",
"process",
".",
"env",
"[",
"key",
".",
"toUpperCase",
"(",
")",
"]",
"||",
"''",
";",
"}"
] | Get the value for an environment variable.
@param {string} key - The name of the environment variable.
@return {string} The value of the environment variable.
@private | [
"Get",
"the",
"value",
"for",
"an",
"environment",
"variable",
"."
] | e0d07a9350568b3a0c3bb28dafd3766206961a02 | https://github.com/Rob--W/proxy-from-env/blob/e0d07a9350568b3a0c3bb28dafd3766206961a02/index.js#L99-L101 |
32,944 | BorisChumichev/everpolate | lib/step.js | step | function step (pointsToEvaluate, functionValuesX, functionValuesY) {
return help.makeItArrayIfItsNot(pointsToEvaluate).map(function (point) {
return functionValuesY[help.findIntervalLeftBorderIndex(point, functionValuesX)]
})
} | javascript | function step (pointsToEvaluate, functionValuesX, functionValuesY) {
return help.makeItArrayIfItsNot(pointsToEvaluate).map(function (point) {
return functionValuesY[help.findIntervalLeftBorderIndex(point, functionValuesX)]
})
} | [
"function",
"step",
"(",
"pointsToEvaluate",
",",
"functionValuesX",
",",
"functionValuesY",
")",
"{",
"return",
"help",
".",
"makeItArrayIfItsNot",
"(",
"pointsToEvaluate",
")",
".",
"map",
"(",
"function",
"(",
"point",
")",
"{",
"return",
"functionValuesY",
"... | Evaluates interpolating step function at the set of numbers
or at a single number
@param {Number|Array} pointsToEvaluate number or set of numbers
for which step is calculated
@param {Array} functionValuesX set of distinct x values
@param {Array} functionValuesY set of distinct y=f(x) values
@returns {Array} | [
"Evaluates",
"interpolating",
"step",
"function",
"at",
"the",
"set",
"of",
"numbers",
"or",
"at",
"a",
"single",
"number"
] | 00201c964891d37e8cfa6922057c5069db4a37d4 | https://github.com/BorisChumichev/everpolate/blob/00201c964891d37e8cfa6922057c5069db4a37d4/lib/step.js#L18-L22 |
32,945 | umakantp/jsmart | src/parser/parser.js | function (template) {
var tree = this.getTree(template)
var runTimePlugins
// Copy so far runtime plugins were generated.
runTimePlugins = this.runTimePlugins
var blocks = this.blocks
var outerBlocks = this.outerBlocks
this.clear()
// Nope, we do not want to clear the cache.
// Refactor to maintain cache. Until that keep commented.
// this.files = {};
return {
tree: tree,
runTimePlugins: runTimePlugins,
blocks: blocks,
outerBlocks: outerBlocks
}
} | javascript | function (template) {
var tree = this.getTree(template)
var runTimePlugins
// Copy so far runtime plugins were generated.
runTimePlugins = this.runTimePlugins
var blocks = this.blocks
var outerBlocks = this.outerBlocks
this.clear()
// Nope, we do not want to clear the cache.
// Refactor to maintain cache. Until that keep commented.
// this.files = {};
return {
tree: tree,
runTimePlugins: runTimePlugins,
blocks: blocks,
outerBlocks: outerBlocks
}
} | [
"function",
"(",
"template",
")",
"{",
"var",
"tree",
"=",
"this",
".",
"getTree",
"(",
"template",
")",
"var",
"runTimePlugins",
"// Copy so far runtime plugins were generated.",
"runTimePlugins",
"=",
"this",
".",
"runTimePlugins",
"var",
"blocks",
"=",
"this",
... | Parse the template and return the data. | [
"Parse",
"the",
"template",
"and",
"return",
"the",
"data",
"."
] | 6168e50baa0b4a81605bbcd907108d4bf921b0a7 | https://github.com/umakantp/jsmart/blob/6168e50baa0b4a81605bbcd907108d4bf921b0a7/src/parser/parser.js#L82-L103 | |
32,946 | umakantp/jsmart | src/parser/parser.js | function (expressionClose, expressionOpen, s) {
var sInner = ''
var closeTag = null
var openTag = null
var findIndex = 0
do {
if (closeTag) {
findIndex += closeTag[0].length
}
closeTag = this.findTag(expressionClose, s)
if (!closeTag) {
throw new Error('Unclosed ' + this.ldelim + expressionOpen + this.rdelim)
}
sInner += s.slice(0, closeTag.index)
findIndex += closeTag.index
s = s.slice((closeTag.index + closeTag[0].length))
openTag = this.findTag(expressionOpen, sInner)
if (openTag) {
sInner = sInner.slice((openTag.index + openTag[0].length))
}
} while (openTag)
closeTag.index = findIndex
return closeTag
} | javascript | function (expressionClose, expressionOpen, s) {
var sInner = ''
var closeTag = null
var openTag = null
var findIndex = 0
do {
if (closeTag) {
findIndex += closeTag[0].length
}
closeTag = this.findTag(expressionClose, s)
if (!closeTag) {
throw new Error('Unclosed ' + this.ldelim + expressionOpen + this.rdelim)
}
sInner += s.slice(0, closeTag.index)
findIndex += closeTag.index
s = s.slice((closeTag.index + closeTag[0].length))
openTag = this.findTag(expressionOpen, sInner)
if (openTag) {
sInner = sInner.slice((openTag.index + openTag[0].length))
}
} while (openTag)
closeTag.index = findIndex
return closeTag
} | [
"function",
"(",
"expressionClose",
",",
"expressionOpen",
",",
"s",
")",
"{",
"var",
"sInner",
"=",
"''",
"var",
"closeTag",
"=",
"null",
"var",
"openTag",
"=",
"null",
"var",
"findIndex",
"=",
"0",
"do",
"{",
"if",
"(",
"closeTag",
")",
"{",
"findInd... | Find closing tag which matches. expressionClose. | [
"Find",
"closing",
"tag",
"which",
"matches",
".",
"expressionClose",
"."
] | 6168e50baa0b4a81605bbcd907108d4bf921b0a7 | https://github.com/umakantp/jsmart/blob/6168e50baa0b4a81605bbcd907108d4bf921b0a7/src/parser/parser.js#L252-L277 | |
32,947 | umakantp/jsmart | src/parser/parser.js | function (s) {
var tree = []
var value = ''
var data
// TODO Refactor, to get this removed.
this.lastTreeInExpression = tree
while (true) {
data = this.lookUp(s.slice(value.length), value)
if (data) {
tree = tree.concat(data.tree)
value = data.value
this.lastTreeInExpression = tree
if (!data.ret) {
break
}
} else {
break
}
}
if (tree.length) {
tree = this.composeExpression(tree)
}
return {tree: tree, value: value}
} | javascript | function (s) {
var tree = []
var value = ''
var data
// TODO Refactor, to get this removed.
this.lastTreeInExpression = tree
while (true) {
data = this.lookUp(s.slice(value.length), value)
if (data) {
tree = tree.concat(data.tree)
value = data.value
this.lastTreeInExpression = tree
if (!data.ret) {
break
}
} else {
break
}
}
if (tree.length) {
tree = this.composeExpression(tree)
}
return {tree: tree, value: value}
} | [
"function",
"(",
"s",
")",
"{",
"var",
"tree",
"=",
"[",
"]",
"var",
"value",
"=",
"''",
"var",
"data",
"// TODO Refactor, to get this removed.",
"this",
".",
"lastTreeInExpression",
"=",
"tree",
"while",
"(",
"true",
")",
"{",
"data",
"=",
"this",
".",
... | Parse expression. | [
"Parse",
"expression",
"."
] | 6168e50baa0b4a81605bbcd907108d4bf921b0a7 | https://github.com/umakantp/jsmart/blob/6168e50baa0b4a81605bbcd907108d4bf921b0a7/src/parser/parser.js#L592-L617 | |
32,948 | umakantp/jsmart | src/parser/parser.js | function (text) {
var tree = []
if (this.parseEmbeddedVars) {
var re = /([$][\w@]+)|`([^`]*)`/
for (var found = re.exec(text); found; found = re.exec(text)) {
tree.push({type: 'text', data: text.slice(0, found.index)})
var d = this.parseExpression(found[1] ? found[1] : found[2])
tree.push(d.tree)
text = text.slice(found.index + found[0].length)
}
}
tree.push({type: 'text', data: text})
return tree
} | javascript | function (text) {
var tree = []
if (this.parseEmbeddedVars) {
var re = /([$][\w@]+)|`([^`]*)`/
for (var found = re.exec(text); found; found = re.exec(text)) {
tree.push({type: 'text', data: text.slice(0, found.index)})
var d = this.parseExpression(found[1] ? found[1] : found[2])
tree.push(d.tree)
text = text.slice(found.index + found[0].length)
}
}
tree.push({type: 'text', data: text})
return tree
} | [
"function",
"(",
"text",
")",
"{",
"var",
"tree",
"=",
"[",
"]",
"if",
"(",
"this",
".",
"parseEmbeddedVars",
")",
"{",
"var",
"re",
"=",
"/",
"([$][\\w@]+)|`([^`]*)`",
"/",
"for",
"(",
"var",
"found",
"=",
"re",
".",
"exec",
"(",
"text",
")",
";",... | Parse text. | [
"Parse",
"text",
"."
] | 6168e50baa0b4a81605bbcd907108d4bf921b0a7 | https://github.com/umakantp/jsmart/blob/6168e50baa0b4a81605bbcd907108d4bf921b0a7/src/parser/parser.js#L625-L639 | |
32,949 | umakantp/jsmart | src/parser/parser.js | function (tpl) {
var ldelim = new RegExp(this.ldelim + '\\*')
var rdelim = new RegExp('\\*' + this.rdelim)
var newTpl = ''
for (var openTag = tpl.match(ldelim); openTag; openTag = tpl.match(ldelim)) {
newTpl += tpl.slice(0, openTag.index)
tpl = tpl.slice(openTag.index + openTag[0].length)
var closeTag = tpl.match(rdelim)
if (!closeTag) {
throw new Error('Unclosed ' + ldelim + '*')
}
tpl = tpl.slice(closeTag.index + closeTag[0].length)
}
return newTpl + tpl
} | javascript | function (tpl) {
var ldelim = new RegExp(this.ldelim + '\\*')
var rdelim = new RegExp('\\*' + this.rdelim)
var newTpl = ''
for (var openTag = tpl.match(ldelim); openTag; openTag = tpl.match(ldelim)) {
newTpl += tpl.slice(0, openTag.index)
tpl = tpl.slice(openTag.index + openTag[0].length)
var closeTag = tpl.match(rdelim)
if (!closeTag) {
throw new Error('Unclosed ' + ldelim + '*')
}
tpl = tpl.slice(closeTag.index + closeTag[0].length)
}
return newTpl + tpl
} | [
"function",
"(",
"tpl",
")",
"{",
"var",
"ldelim",
"=",
"new",
"RegExp",
"(",
"this",
".",
"ldelim",
"+",
"'\\\\*'",
")",
"var",
"rdelim",
"=",
"new",
"RegExp",
"(",
"'\\\\*'",
"+",
"this",
".",
"rdelim",
")",
"var",
"newTpl",
"=",
"''",
"for",
"("... | Remove comments. We do not want to parse them anyway. | [
"Remove",
"comments",
".",
"We",
"do",
"not",
"want",
"to",
"parse",
"them",
"anyway",
"."
] | 6168e50baa0b4a81605bbcd907108d4bf921b0a7 | https://github.com/umakantp/jsmart/blob/6168e50baa0b4a81605bbcd907108d4bf921b0a7/src/parser/parser.js#L657-L672 | |
32,950 | umakantp/jsmart | dist/jsmart.js | findInArray | function findInArray (arr, val) {
if (Array.prototype.indexOf) {
return arr.indexOf(val)
}
for (var i = 0; i < arr.length; ++i) {
if (arr[i] === val) {
return i
}
}
return -1
} | javascript | function findInArray (arr, val) {
if (Array.prototype.indexOf) {
return arr.indexOf(val)
}
for (var i = 0; i < arr.length; ++i) {
if (arr[i] === val) {
return i
}
}
return -1
} | [
"function",
"findInArray",
"(",
"arr",
",",
"val",
")",
"{",
"if",
"(",
"Array",
".",
"prototype",
".",
"indexOf",
")",
"{",
"return",
"arr",
".",
"indexOf",
"(",
"val",
")",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"arr",
".",
"le... | Find in array. | [
"Find",
"in",
"array",
"."
] | 6168e50baa0b4a81605bbcd907108d4bf921b0a7 | https://github.com/umakantp/jsmart/blob/6168e50baa0b4a81605bbcd907108d4bf921b0a7/dist/jsmart.js#L58-L68 |
32,951 | umakantp/jsmart | dist/jsmart.js | function (tree, data) {
// Process the tree and get the output.
var output = this.process(tree, data)
if (this.debugging) {
this.plugins.debug.process([], {
includedTemplates: this.includedTemplates,
assignedVars: data
})
}
this.clear()
return {
output: output.tpl,
smarty: output.smarty
}
} | javascript | function (tree, data) {
// Process the tree and get the output.
var output = this.process(tree, data)
if (this.debugging) {
this.plugins.debug.process([], {
includedTemplates: this.includedTemplates,
assignedVars: data
})
}
this.clear()
return {
output: output.tpl,
smarty: output.smarty
}
} | [
"function",
"(",
"tree",
",",
"data",
")",
"{",
"// Process the tree and get the output.",
"var",
"output",
"=",
"this",
".",
"process",
"(",
"tree",
",",
"data",
")",
"if",
"(",
"this",
".",
"debugging",
")",
"{",
"this",
".",
"plugins",
".",
"debug",
"... | Process the tree and return the data. | [
"Process",
"the",
"tree",
"and",
"return",
"the",
"data",
"."
] | 6168e50baa0b4a81605bbcd907108d4bf921b0a7 | https://github.com/umakantp/jsmart/blob/6168e50baa0b4a81605bbcd907108d4bf921b0a7/dist/jsmart.js#L1504-L1519 | |
32,952 | umakantp/jsmart | dist/jsmart.js | function (tree, data) {
var res = ''
var s
var node
var tmp
var plugin
for (var i = 0; i < tree.length; ++i) {
node = tree[i]
s = ''
if (node.type === 'text') {
s = node.data
} else if (node.type === 'var') {
s = this.getVarValue(node, data)
} else if (node.type === 'boolean') {
s = !!node.data
} else if (node.type === 'build-in') {
tmp = this.buildInFunctions[node.name].process.call(this, node, data)
if (typeof tmp.tpl !== 'undefined') {
// If tmp is object, which means it has modified, data also
// so copy it back to data.
s = tmp.tpl
data = tmp.data
} else {
// If tmp is string means it has not modified data.
s = tmp
}
} else if (node.type === 'plugin') {
if (this.runTimePlugins[node.name]) {
// Thats call for {function}.
tmp = this.buildInFunctions['function'].process.call(this, node, data)
if (typeof tmp.tpl !== 'undefined') {
// If tmp is object, which means it has modified, data also
// so copy it back to data.
s = tmp.tpl
data = tmp.data
} else {
// If tmp is string means it has not modified data.
s = tmp
}
} else {
plugin = this.plugins[node.name]
if (plugin.type === 'block') {
var repeat = {value: true}
while (repeat.value) {
repeat.value = false
tmp = this.process(node.subTree, data)
if (typeof tmp.tpl !== 'undefined') {
data = tmp.data
tmp = tmp.tpl
}
s += plugin.process.call(
this,
this.getActualParamValues(node.params, data),
tmp,
data,
repeat
)
}
} else if (plugin.type === 'function') {
s = plugin.process.call(this, this.getActualParamValues(node.params, data), data)
}
}
}
if (typeof s === 'boolean' && tree.length !== 1) {
s = s ? '1' : ''
}
if (s === null || s === undefined) {
s = ''
}
if (tree.length === 1) {
return {tpl: s, data: data}
}
res += ((s !== null) ? s : '')
if (data.smarty.continue || data.smarty.break) {
return {tpl: res, data: data}
}
}
return {tpl: res, data: data}
} | javascript | function (tree, data) {
var res = ''
var s
var node
var tmp
var plugin
for (var i = 0; i < tree.length; ++i) {
node = tree[i]
s = ''
if (node.type === 'text') {
s = node.data
} else if (node.type === 'var') {
s = this.getVarValue(node, data)
} else if (node.type === 'boolean') {
s = !!node.data
} else if (node.type === 'build-in') {
tmp = this.buildInFunctions[node.name].process.call(this, node, data)
if (typeof tmp.tpl !== 'undefined') {
// If tmp is object, which means it has modified, data also
// so copy it back to data.
s = tmp.tpl
data = tmp.data
} else {
// If tmp is string means it has not modified data.
s = tmp
}
} else if (node.type === 'plugin') {
if (this.runTimePlugins[node.name]) {
// Thats call for {function}.
tmp = this.buildInFunctions['function'].process.call(this, node, data)
if (typeof tmp.tpl !== 'undefined') {
// If tmp is object, which means it has modified, data also
// so copy it back to data.
s = tmp.tpl
data = tmp.data
} else {
// If tmp is string means it has not modified data.
s = tmp
}
} else {
plugin = this.plugins[node.name]
if (plugin.type === 'block') {
var repeat = {value: true}
while (repeat.value) {
repeat.value = false
tmp = this.process(node.subTree, data)
if (typeof tmp.tpl !== 'undefined') {
data = tmp.data
tmp = tmp.tpl
}
s += plugin.process.call(
this,
this.getActualParamValues(node.params, data),
tmp,
data,
repeat
)
}
} else if (plugin.type === 'function') {
s = plugin.process.call(this, this.getActualParamValues(node.params, data), data)
}
}
}
if (typeof s === 'boolean' && tree.length !== 1) {
s = s ? '1' : ''
}
if (s === null || s === undefined) {
s = ''
}
if (tree.length === 1) {
return {tpl: s, data: data}
}
res += ((s !== null) ? s : '')
if (data.smarty.continue || data.smarty.break) {
return {tpl: res, data: data}
}
}
return {tpl: res, data: data}
} | [
"function",
"(",
"tree",
",",
"data",
")",
"{",
"var",
"res",
"=",
"''",
"var",
"s",
"var",
"node",
"var",
"tmp",
"var",
"plugin",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"tree",
".",
"length",
";",
"++",
"i",
")",
"{",
"node",
"=",
... | Process the tree and apply data. | [
"Process",
"the",
"tree",
"and",
"apply",
"data",
"."
] | 6168e50baa0b4a81605bbcd907108d4bf921b0a7 | https://github.com/umakantp/jsmart/blob/6168e50baa0b4a81605bbcd907108d4bf921b0a7/dist/jsmart.js#L1522-L1603 | |
32,953 | umakantp/jsmart | dist/jsmart.js | function (template, options) {
var parsedTemplate
if (!options) {
options = {}
}
if (options.rdelim) {
// If delimiters are passed locally take them.
this.smarty.rdelim = options.rdelim
} else if (jSmart.prototype.right_delimiter) {
// Backward compatible. Old way to set via prototype.
this.smarty.rdelim = jSmart.prototype.right_delimiter
} else {
// Otherwise default delimiters
this.smarty.rdelim = '}'
}
if (options.ldelim) {
// If delimiters are passed locally take them.
this.smarty.ldelim = options.ldelim
} else if (jSmart.prototype.left_delimiter) {
// Backward compatible. Old way to set via prototype.
this.smarty.ldelim = jSmart.prototype.left_delimiter
} else {
// Otherwise default delimiters
this.smarty.ldelim = '{'
}
if (options.autoLiteral !== undefined) {
// If autoLiteral is passed locally, take it.
this.autoLiteral = options.autoLiteral
} else if (jSmart.prototype.auto_literal !== undefined) {
// Backward compatible. Old way to set via prototype.
this.autoLiteral = jSmart.prototype.auto_literal
}
if (options.debugging !== undefined) {
// If debugging is passed locally, take it.
this.debugging = options.debugging
} else if (jSmart.prototype.debugging !== undefined) {
// Backward compatible. Old way to set via prototype.
this.debugging = jSmart.prototype.debugging
}
if (options.escapeHtml !== undefined) {
// If escapeHtml is passed locally, take it.
this.escapeHtml = options.escapeHtml
} else if (jSmart.prototype.escape_html !== undefined) {
// Backward compatible. Old way to set via prototype.
this.escapeHtml = jSmart.prototype.escape_html
}
// Is template string or at least defined?!
template = String(template || '')
// Generate the tree. We pass delimiters and many config values
// which are needed by parser to parse like delimiters.
jSmartParser.clear()
jSmartParser.rdelim = this.smarty.rdelim
jSmartParser.ldelim = this.smarty.ldelim
jSmartParser.getTemplate = this.getTemplate
jSmartParser.getConfig = this.getConfig
jSmartParser.autoLiteral = this.autoLiteral
jSmartParser.plugins = this.plugins
jSmartParser.preFilters = this.filtersGlobal.pre
// Above parser config are set, lets parse.
parsedTemplate = jSmartParser.getParsed(template)
this.tree = parsedTemplate.tree
this.runTimePlugins = parsedTemplate.runTimePlugins
this.blocks = parsedTemplate.blocks
this.outerBlocks = parsedTemplate.outerBlocks
} | javascript | function (template, options) {
var parsedTemplate
if (!options) {
options = {}
}
if (options.rdelim) {
// If delimiters are passed locally take them.
this.smarty.rdelim = options.rdelim
} else if (jSmart.prototype.right_delimiter) {
// Backward compatible. Old way to set via prototype.
this.smarty.rdelim = jSmart.prototype.right_delimiter
} else {
// Otherwise default delimiters
this.smarty.rdelim = '}'
}
if (options.ldelim) {
// If delimiters are passed locally take them.
this.smarty.ldelim = options.ldelim
} else if (jSmart.prototype.left_delimiter) {
// Backward compatible. Old way to set via prototype.
this.smarty.ldelim = jSmart.prototype.left_delimiter
} else {
// Otherwise default delimiters
this.smarty.ldelim = '{'
}
if (options.autoLiteral !== undefined) {
// If autoLiteral is passed locally, take it.
this.autoLiteral = options.autoLiteral
} else if (jSmart.prototype.auto_literal !== undefined) {
// Backward compatible. Old way to set via prototype.
this.autoLiteral = jSmart.prototype.auto_literal
}
if (options.debugging !== undefined) {
// If debugging is passed locally, take it.
this.debugging = options.debugging
} else if (jSmart.prototype.debugging !== undefined) {
// Backward compatible. Old way to set via prototype.
this.debugging = jSmart.prototype.debugging
}
if (options.escapeHtml !== undefined) {
// If escapeHtml is passed locally, take it.
this.escapeHtml = options.escapeHtml
} else if (jSmart.prototype.escape_html !== undefined) {
// Backward compatible. Old way to set via prototype.
this.escapeHtml = jSmart.prototype.escape_html
}
// Is template string or at least defined?!
template = String(template || '')
// Generate the tree. We pass delimiters and many config values
// which are needed by parser to parse like delimiters.
jSmartParser.clear()
jSmartParser.rdelim = this.smarty.rdelim
jSmartParser.ldelim = this.smarty.ldelim
jSmartParser.getTemplate = this.getTemplate
jSmartParser.getConfig = this.getConfig
jSmartParser.autoLiteral = this.autoLiteral
jSmartParser.plugins = this.plugins
jSmartParser.preFilters = this.filtersGlobal.pre
// Above parser config are set, lets parse.
parsedTemplate = jSmartParser.getParsed(template)
this.tree = parsedTemplate.tree
this.runTimePlugins = parsedTemplate.runTimePlugins
this.blocks = parsedTemplate.blocks
this.outerBlocks = parsedTemplate.outerBlocks
} | [
"function",
"(",
"template",
",",
"options",
")",
"{",
"var",
"parsedTemplate",
"if",
"(",
"!",
"options",
")",
"{",
"options",
"=",
"{",
"}",
"}",
"if",
"(",
"options",
".",
"rdelim",
")",
"{",
"// If delimiters are passed locally take them.",
"this",
".",
... | Initialize, jSmart, set settings and parse the template. | [
"Initialize",
"jSmart",
"set",
"settings",
"and",
"parse",
"the",
"template",
"."
] | 6168e50baa0b4a81605bbcd907108d4bf921b0a7 | https://github.com/umakantp/jsmart/blob/6168e50baa0b4a81605bbcd907108d4bf921b0a7/dist/jsmart.js#L2485-L2553 | |
32,954 | umakantp/jsmart | dist/jsmart.js | function (data) {
var outputData = ''
if (!(typeof data === 'object')) {
data = {}
}
// Define smarty inside data and copy smarty vars, so one can use $smarty
// vars inside templates.
data.smarty = {}
objectMerge(data.smarty, this.smarty)
// Take default global modifiers, add with local default modifiers.
// Merge them and keep them cached.
this.globalAndDefaultModifiers = jSmart.prototype.defaultModifiersGlobal.concat(this.defaultModifiers)
// Take default global filters, add with local default filters.
// Merge them and keep them cached.
this.globalAndDefaultFilters = jSmart.prototype.filtersGlobal.variable.concat(this.filters.variable)
jSmartProcessor.clear()
jSmartProcessor.plugins = this.plugins
jSmartProcessor.modifiers = this.modifiers
jSmartProcessor.defaultModifiers = this.defaultModifiers
jSmartProcessor.escapeHtml = this.escapeHtml
jSmartProcessor.variableFilters = this.globalAndDefaultFilters
jSmartProcessor.runTimePlugins = this.runTimePlugins
jSmartProcessor.blocks = this.blocks
jSmartProcessor.outerBlocks = this.outerBlocks
jSmartProcessor.debugging = this.debugging
// Capture the output by processing the template.
outputData = jSmartProcessor.getProcessed(this.tree, data, this.smarty)
// Merge back smarty data returned by process to original object.
objectMerge(this.smarty, outputData.smarty)
// Apply post filters to output and return the template data.
return this.applyFilters(jSmart.prototype.filtersGlobal.post.concat(this.filters.post), outputData.output)
} | javascript | function (data) {
var outputData = ''
if (!(typeof data === 'object')) {
data = {}
}
// Define smarty inside data and copy smarty vars, so one can use $smarty
// vars inside templates.
data.smarty = {}
objectMerge(data.smarty, this.smarty)
// Take default global modifiers, add with local default modifiers.
// Merge them and keep them cached.
this.globalAndDefaultModifiers = jSmart.prototype.defaultModifiersGlobal.concat(this.defaultModifiers)
// Take default global filters, add with local default filters.
// Merge them and keep them cached.
this.globalAndDefaultFilters = jSmart.prototype.filtersGlobal.variable.concat(this.filters.variable)
jSmartProcessor.clear()
jSmartProcessor.plugins = this.plugins
jSmartProcessor.modifiers = this.modifiers
jSmartProcessor.defaultModifiers = this.defaultModifiers
jSmartProcessor.escapeHtml = this.escapeHtml
jSmartProcessor.variableFilters = this.globalAndDefaultFilters
jSmartProcessor.runTimePlugins = this.runTimePlugins
jSmartProcessor.blocks = this.blocks
jSmartProcessor.outerBlocks = this.outerBlocks
jSmartProcessor.debugging = this.debugging
// Capture the output by processing the template.
outputData = jSmartProcessor.getProcessed(this.tree, data, this.smarty)
// Merge back smarty data returned by process to original object.
objectMerge(this.smarty, outputData.smarty)
// Apply post filters to output and return the template data.
return this.applyFilters(jSmart.prototype.filtersGlobal.post.concat(this.filters.post), outputData.output)
} | [
"function",
"(",
"data",
")",
"{",
"var",
"outputData",
"=",
"''",
"if",
"(",
"!",
"(",
"typeof",
"data",
"===",
"'object'",
")",
")",
"{",
"data",
"=",
"{",
"}",
"}",
"// Define smarty inside data and copy smarty vars, so one can use $smarty",
"// vars inside tem... | Process the generated tree. | [
"Process",
"the",
"generated",
"tree",
"."
] | 6168e50baa0b4a81605bbcd907108d4bf921b0a7 | https://github.com/umakantp/jsmart/blob/6168e50baa0b4a81605bbcd907108d4bf921b0a7/dist/jsmart.js#L2556-L2593 | |
32,955 | umakantp/jsmart | dist/jsmart.js | function (toPrint, indent, indentEnd) {
if (!indent) {
indent = ' '
}
if (!indentEnd) {
indentEnd = ''
}
var s = ''
var name
if (toPrint instanceof Object) {
s = 'Object (\n'
for (name in toPrint) {
if (toPrint.hasOwnProperty(name)) {
s += indent + indent + '[' + name + '] => ' + this.printR(toPrint[name], indent + ' ', indent + indent)
}
}
s += indentEnd + ')\n'
return s
} else if (toPrint instanceof Array) {
s = 'Array (\n'
for (name in toPrint) {
if (toPrint.hasOwnProperty(name)) {
s += indent + indent + '[' + name + '] => ' + this.printR(toPrint[name], indent + ' ', indent + indent)
}
}
s += indentEnd + ')\n'
return s
} else if (toPrint instanceof Boolean) {
var bool = 'false'
if (bool === true) {
bool = 'true'
}
return bool + '\n'
} else {
return (toPrint + '\n')
}
} | javascript | function (toPrint, indent, indentEnd) {
if (!indent) {
indent = ' '
}
if (!indentEnd) {
indentEnd = ''
}
var s = ''
var name
if (toPrint instanceof Object) {
s = 'Object (\n'
for (name in toPrint) {
if (toPrint.hasOwnProperty(name)) {
s += indent + indent + '[' + name + '] => ' + this.printR(toPrint[name], indent + ' ', indent + indent)
}
}
s += indentEnd + ')\n'
return s
} else if (toPrint instanceof Array) {
s = 'Array (\n'
for (name in toPrint) {
if (toPrint.hasOwnProperty(name)) {
s += indent + indent + '[' + name + '] => ' + this.printR(toPrint[name], indent + ' ', indent + indent)
}
}
s += indentEnd + ')\n'
return s
} else if (toPrint instanceof Boolean) {
var bool = 'false'
if (bool === true) {
bool = 'true'
}
return bool + '\n'
} else {
return (toPrint + '\n')
}
} | [
"function",
"(",
"toPrint",
",",
"indent",
",",
"indentEnd",
")",
"{",
"if",
"(",
"!",
"indent",
")",
"{",
"indent",
"=",
"' '",
"}",
"if",
"(",
"!",
"indentEnd",
")",
"{",
"indentEnd",
"=",
"''",
"}",
"var",
"s",
"=",
"''",
"var",
"name... | Print the object. | [
"Print",
"the",
"object",
"."
] | 6168e50baa0b4a81605bbcd907108d4bf921b0a7 | https://github.com/umakantp/jsmart/blob/6168e50baa0b4a81605bbcd907108d4bf921b0a7/dist/jsmart.js#L2604-L2640 | |
32,956 | umakantp/jsmart | dist/jsmart.js | function (type, name, callback) {
if (type === 'modifier') {
this.modifiers[name] = callback
} else {
this.plugins[name] = {'type': type, 'process': callback}
}
} | javascript | function (type, name, callback) {
if (type === 'modifier') {
this.modifiers[name] = callback
} else {
this.plugins[name] = {'type': type, 'process': callback}
}
} | [
"function",
"(",
"type",
",",
"name",
",",
"callback",
")",
"{",
"if",
"(",
"type",
"===",
"'modifier'",
")",
"{",
"this",
".",
"modifiers",
"[",
"name",
"]",
"=",
"callback",
"}",
"else",
"{",
"this",
".",
"plugins",
"[",
"name",
"]",
"=",
"{",
... | Register a plugin. | [
"Register",
"a",
"plugin",
"."
] | 6168e50baa0b4a81605bbcd907108d4bf921b0a7 | https://github.com/umakantp/jsmart/blob/6168e50baa0b4a81605bbcd907108d4bf921b0a7/dist/jsmart.js#L2643-L2649 | |
32,957 | umakantp/jsmart | dist/jsmart.js | function (type, callback) {
(this.tree ? this.filters : jSmart.prototype.filtersGlobal)[((type === 'output') ? 'post' : type)].push(callback)
} | javascript | function (type, callback) {
(this.tree ? this.filters : jSmart.prototype.filtersGlobal)[((type === 'output') ? 'post' : type)].push(callback)
} | [
"function",
"(",
"type",
",",
"callback",
")",
"{",
"(",
"this",
".",
"tree",
"?",
"this",
".",
"filters",
":",
"jSmart",
".",
"prototype",
".",
"filtersGlobal",
")",
"[",
"(",
"(",
"type",
"===",
"'output'",
")",
"?",
"'post'",
":",
"type",
")",
"... | Register a filter. | [
"Register",
"a",
"filter",
"."
] | 6168e50baa0b4a81605bbcd907108d4bf921b0a7 | https://github.com/umakantp/jsmart/blob/6168e50baa0b4a81605bbcd907108d4bf921b0a7/dist/jsmart.js#L2652-L2654 | |
32,958 | kupriyanenko/jbone | dist/jbone.js | function(el, types, handler, data, selector) {
jBone.setId(el);
var eventHandler = function(e) {
jBone.event.dispatch.call(el, e);
},
events = jBone.getData(el).events,
eventType, t, event;
types = types.split(" ");
t = types.length;
while (t--) {
event = types[t];
eventType = event.split(".")[0];
events[eventType] = events[eventType] || [];
if (events[eventType].length) {
// override with previous event handler
eventHandler = events[eventType][0].fn;
} else {
el.addEventListener && el.addEventListener(eventType, eventHandler, false);
}
events[eventType].push({
namespace: event.split(".").splice(1).join("."),
fn: eventHandler,
selector: selector,
data: data,
originfn: handler
});
}
} | javascript | function(el, types, handler, data, selector) {
jBone.setId(el);
var eventHandler = function(e) {
jBone.event.dispatch.call(el, e);
},
events = jBone.getData(el).events,
eventType, t, event;
types = types.split(" ");
t = types.length;
while (t--) {
event = types[t];
eventType = event.split(".")[0];
events[eventType] = events[eventType] || [];
if (events[eventType].length) {
// override with previous event handler
eventHandler = events[eventType][0].fn;
} else {
el.addEventListener && el.addEventListener(eventType, eventHandler, false);
}
events[eventType].push({
namespace: event.split(".").splice(1).join("."),
fn: eventHandler,
selector: selector,
data: data,
originfn: handler
});
}
} | [
"function",
"(",
"el",
",",
"types",
",",
"handler",
",",
"data",
",",
"selector",
")",
"{",
"jBone",
".",
"setId",
"(",
"el",
")",
";",
"var",
"eventHandler",
"=",
"function",
"(",
"e",
")",
"{",
"jBone",
".",
"event",
".",
"dispatch",
".",
"call"... | Attach a handler to an event for the elements
@param {Node} el - Events will be attached to this DOM Node
@param {String} types - One or more space-separated event types and optional namespaces
@param {Function} handler - A function to execute when the event is triggered
@param {Object} [data] - Data to be passed to the handler in event.data
@param {String} [selector] - A selector string to filter the descendants of the selected elements | [
"Attach",
"a",
"handler",
"to",
"an",
"event",
"for",
"the",
"elements"
] | 80b99258ef0fcd23f9d7451fbe4d87e73ded94f1 | https://github.com/kupriyanenko/jbone/blob/80b99258ef0fcd23f9d7451fbe4d87e73ded94f1/dist/jbone.js#L336-L368 | |
32,959 | kupriyanenko/jbone | dist/jbone.js | function(el, types, handler, selector) {
var removeListener = function(events, eventType, index, el, e) {
var callback;
// get callback
if ((handler && e.originfn === handler) || !handler) {
callback = e.fn;
}
if (events[eventType][index].fn === callback) {
// remove handler from cache
events[eventType].splice(index, 1);
if (!events[eventType].length) {
el.removeEventListener(eventType, callback);
}
}
},
events = jBone.getData(el).events,
l,
eventsByType;
if (!events) {
return;
}
// remove all events
if (!types && events) {
return keys(events).forEach(function(eventType) {
eventsByType = events[eventType];
l = eventsByType.length;
while(l--) {
removeListener(events, eventType, l, el, eventsByType[l]);
}
});
}
types.split(" ").forEach(function(eventName) {
var eventType = eventName.split(".")[0],
namespace = eventName.split(".").splice(1).join("."),
e;
// remove named events
if (events[eventType]) {
eventsByType = events[eventType];
l = eventsByType.length;
while(l--) {
e = eventsByType[l];
if ((!namespace || (namespace && e.namespace === namespace)) &&
(!selector || (selector && e.selector === selector))) {
removeListener(events, eventType, l, el, e);
}
}
}
// remove all namespaced events
else if (namespace) {
keys(events).forEach(function(eventType) {
eventsByType = events[eventType];
l = eventsByType.length;
while(l--) {
e = eventsByType[l];
if (e.namespace.split(".")[0] === namespace.split(".")[0]) {
removeListener(events, eventType, l, el, e);
}
}
});
}
});
} | javascript | function(el, types, handler, selector) {
var removeListener = function(events, eventType, index, el, e) {
var callback;
// get callback
if ((handler && e.originfn === handler) || !handler) {
callback = e.fn;
}
if (events[eventType][index].fn === callback) {
// remove handler from cache
events[eventType].splice(index, 1);
if (!events[eventType].length) {
el.removeEventListener(eventType, callback);
}
}
},
events = jBone.getData(el).events,
l,
eventsByType;
if (!events) {
return;
}
// remove all events
if (!types && events) {
return keys(events).forEach(function(eventType) {
eventsByType = events[eventType];
l = eventsByType.length;
while(l--) {
removeListener(events, eventType, l, el, eventsByType[l]);
}
});
}
types.split(" ").forEach(function(eventName) {
var eventType = eventName.split(".")[0],
namespace = eventName.split(".").splice(1).join("."),
e;
// remove named events
if (events[eventType]) {
eventsByType = events[eventType];
l = eventsByType.length;
while(l--) {
e = eventsByType[l];
if ((!namespace || (namespace && e.namespace === namespace)) &&
(!selector || (selector && e.selector === selector))) {
removeListener(events, eventType, l, el, e);
}
}
}
// remove all namespaced events
else if (namespace) {
keys(events).forEach(function(eventType) {
eventsByType = events[eventType];
l = eventsByType.length;
while(l--) {
e = eventsByType[l];
if (e.namespace.split(".")[0] === namespace.split(".")[0]) {
removeListener(events, eventType, l, el, e);
}
}
});
}
});
} | [
"function",
"(",
"el",
",",
"types",
",",
"handler",
",",
"selector",
")",
"{",
"var",
"removeListener",
"=",
"function",
"(",
"events",
",",
"eventType",
",",
"index",
",",
"el",
",",
"e",
")",
"{",
"var",
"callback",
";",
"// get callback",
"if",
"("... | Remove an event handler
@param {Node} el - Events will be deattached from this DOM Node
@param {String} types - One or more space-separated event types and optional namespaces
@param {Function} handler - A handler function previously attached for the event(s)
@param {String} [selector] - A selector string to filter the descendants of the selected elements | [
"Remove",
"an",
"event",
"handler"
] | 80b99258ef0fcd23f9d7451fbe4d87e73ded94f1 | https://github.com/kupriyanenko/jbone/blob/80b99258ef0fcd23f9d7451fbe4d87e73ded94f1/dist/jbone.js#L377-L448 | |
32,960 | kupriyanenko/jbone | dist/jbone.js | function(el, event) {
var events = [];
if (isString(event)) {
events = event.split(" ").map(function(event) {
return jBone.Event(event);
});
} else {
event = event instanceof Event ? event : jBone.Event(event);
events = [event];
}
events.forEach(function(event) {
if (!event.type) {
return;
}
el.dispatchEvent && el.dispatchEvent(event);
});
} | javascript | function(el, event) {
var events = [];
if (isString(event)) {
events = event.split(" ").map(function(event) {
return jBone.Event(event);
});
} else {
event = event instanceof Event ? event : jBone.Event(event);
events = [event];
}
events.forEach(function(event) {
if (!event.type) {
return;
}
el.dispatchEvent && el.dispatchEvent(event);
});
} | [
"function",
"(",
"el",
",",
"event",
")",
"{",
"var",
"events",
"=",
"[",
"]",
";",
"if",
"(",
"isString",
"(",
"event",
")",
")",
"{",
"events",
"=",
"event",
".",
"split",
"(",
"\" \"",
")",
".",
"map",
"(",
"function",
"(",
"event",
")",
"{"... | Execute all handlers and behaviors attached to the matched elements for the given event type.
@param {Node} el - Events will be triggered for thie DOM Node
@param {String} event - One or more space-separated event types and optional namespaces | [
"Execute",
"all",
"handlers",
"and",
"behaviors",
"attached",
"to",
"the",
"matched",
"elements",
"for",
"the",
"given",
"event",
"type",
"."
] | 80b99258ef0fcd23f9d7451fbe4d87e73ded94f1 | https://github.com/kupriyanenko/jbone/blob/80b99258ef0fcd23f9d7451fbe4d87e73ded94f1/dist/jbone.js#L455-L474 | |
32,961 | bhoriuchi/readline-promise | lib/index.js | each | function each(cfg) {
return function(callback) {
return new Promise(function(resolve, reject) {
// create an array to store callbacks
var rl, cbs = [];
// create an interface
try {
rl = readline.createInterface(cfg);
}
catch(err) {
return reject(err);
}
// handle a new line
rl.on('line', function(line) {
cbs.push(callback(line));
});
// handle close
rl.on('close', function() {
Promise.all(cbs).then(function() {
resolve({
lines: cbs.length
});
})
.caught(function(err) {
reject(err);
});
});
});
};
} | javascript | function each(cfg) {
return function(callback) {
return new Promise(function(resolve, reject) {
// create an array to store callbacks
var rl, cbs = [];
// create an interface
try {
rl = readline.createInterface(cfg);
}
catch(err) {
return reject(err);
}
// handle a new line
rl.on('line', function(line) {
cbs.push(callback(line));
});
// handle close
rl.on('close', function() {
Promise.all(cbs).then(function() {
resolve({
lines: cbs.length
});
})
.caught(function(err) {
reject(err);
});
});
});
};
} | [
"function",
"each",
"(",
"cfg",
")",
"{",
"return",
"function",
"(",
"callback",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"// create an array to store callbacks",
"var",
"rl",
",",
"cbs",
"=",
"[",
"]"... | calls the callback on each line then resolves the callbacks if they are promises | [
"calls",
"the",
"callback",
"on",
"each",
"line",
"then",
"resolves",
"the",
"callbacks",
"if",
"they",
"are",
"promises"
] | 9bb8d1d80a9f0fca91bf99c16b57e281fc424d4a | https://github.com/bhoriuchi/readline-promise/blob/9bb8d1d80a9f0fca91bf99c16b57e281fc424d4a/lib/index.js#L12-L45 |
32,962 | kriskowal/q-connection | q-connection.js | function (message) {
// forward the message to the local promise,
// which will return a response promise
var local = getLocal(message.to).promise;
var response = local.dispatch(message.op, decode(message.args));
var envelope;
// connect the local response promise with the
// remote response promise:
// if the value is ever resolved, send the
// fulfilled value across the wire
response.then(function (resolution) {
try {
resolution = encode(resolution);
} catch (exception) {
try {
resolution = {"!": encode(exception)};
} catch (_exception) {
resolution = {"!": null};
}
}
envelope = JSON.stringify({
"type": "resolve",
"to": message.from,
"resolution": resolution
});
connection.put(envelope);
}, function (reason) {
try {
reason = encode(reason);
} catch (exception) {
try {
reason = encode(exception);
} catch (_exception) {
reason = null;
}
}
envelope = JSON.stringify({
"type": "resolve",
"to": message.from,
"resolution": {"!": reason}
});
connection.put(envelope);
}, function (progress) {
try {
progress = encode(progress);
envelope = JSON.stringify({
"type": "notify",
"to": message.from,
"resolution": progress
});
} catch (exception) {
try {
progress = {"!": encode(exception)};
} catch (_exception) {
progress = {"!": null};
}
envelope = JSON.stringify({
"type": "resolve",
"to": message.from,
"resolution": progress
});
}
connection.put(envelope);
})
.done();
} | javascript | function (message) {
// forward the message to the local promise,
// which will return a response promise
var local = getLocal(message.to).promise;
var response = local.dispatch(message.op, decode(message.args));
var envelope;
// connect the local response promise with the
// remote response promise:
// if the value is ever resolved, send the
// fulfilled value across the wire
response.then(function (resolution) {
try {
resolution = encode(resolution);
} catch (exception) {
try {
resolution = {"!": encode(exception)};
} catch (_exception) {
resolution = {"!": null};
}
}
envelope = JSON.stringify({
"type": "resolve",
"to": message.from,
"resolution": resolution
});
connection.put(envelope);
}, function (reason) {
try {
reason = encode(reason);
} catch (exception) {
try {
reason = encode(exception);
} catch (_exception) {
reason = null;
}
}
envelope = JSON.stringify({
"type": "resolve",
"to": message.from,
"resolution": {"!": reason}
});
connection.put(envelope);
}, function (progress) {
try {
progress = encode(progress);
envelope = JSON.stringify({
"type": "notify",
"to": message.from,
"resolution": progress
});
} catch (exception) {
try {
progress = {"!": encode(exception)};
} catch (_exception) {
progress = {"!": null};
}
envelope = JSON.stringify({
"type": "resolve",
"to": message.from,
"resolution": progress
});
}
connection.put(envelope);
})
.done();
} | [
"function",
"(",
"message",
")",
"{",
"// forward the message to the local promise,",
"// which will return a response promise",
"var",
"local",
"=",
"getLocal",
"(",
"message",
".",
"to",
")",
".",
"promise",
";",
"var",
"response",
"=",
"local",
".",
"dispatch",
"... | a "send" message forwards messages from a remote promise to a local promise. | [
"a",
"send",
"message",
"forwards",
"messages",
"from",
"a",
"remote",
"promise",
"to",
"a",
"local",
"promise",
"."
] | 85fad079361a1a755004ebec08e7b5fc3455a36c | https://github.com/kriskowal/q-connection/blob/85fad079361a1a755004ebec08e7b5fc3455a36c/q-connection.js#L100-L169 | |
32,963 | kriskowal/q-connection | q-connection.js | makeLocal | function makeLocal(id) {
if (hasLocal(id)) {
return getLocal(id).promise;
} else {
var deferred = Q.defer();
locals.set(id, deferred);
return deferred.promise;
}
} | javascript | function makeLocal(id) {
if (hasLocal(id)) {
return getLocal(id).promise;
} else {
var deferred = Q.defer();
locals.set(id, deferred);
return deferred.promise;
}
} | [
"function",
"makeLocal",
"(",
"id",
")",
"{",
"if",
"(",
"hasLocal",
"(",
"id",
")",
")",
"{",
"return",
"getLocal",
"(",
"id",
")",
".",
"promise",
";",
"}",
"else",
"{",
"var",
"deferred",
"=",
"Q",
".",
"defer",
"(",
")",
";",
"locals",
".",
... | construct a local promise, such that it can be resolved later by a remote message | [
"construct",
"a",
"local",
"promise",
"such",
"that",
"it",
"can",
"be",
"resolved",
"later",
"by",
"a",
"remote",
"message"
] | 85fad079361a1a755004ebec08e7b5fc3455a36c | https://github.com/kriskowal/q-connection/blob/85fad079361a1a755004ebec08e7b5fc3455a36c/q-connection.js#L182-L190 |
32,964 | kriskowal/q-connection | q-connection.js | makeRemote | function makeRemote(id) {
var remotePromise = Q.makePromise({
when: function () {
return this;
}
}, function (op, args) {
var localId = makeId();
var response = makeLocal(localId);
_debug("sending:", "R" + JSON.stringify(id), JSON.stringify(op), JSON.stringify(encode(args)));
connection.put(JSON.stringify({
"type": "send",
"to": id,
"from": localId,
"op": op,
"args": encode(args)
}));
return response;
});
remotes.set(r,id);
return remotePromise;
} | javascript | function makeRemote(id) {
var remotePromise = Q.makePromise({
when: function () {
return this;
}
}, function (op, args) {
var localId = makeId();
var response = makeLocal(localId);
_debug("sending:", "R" + JSON.stringify(id), JSON.stringify(op), JSON.stringify(encode(args)));
connection.put(JSON.stringify({
"type": "send",
"to": id,
"from": localId,
"op": op,
"args": encode(args)
}));
return response;
});
remotes.set(r,id);
return remotePromise;
} | [
"function",
"makeRemote",
"(",
"id",
")",
"{",
"var",
"remotePromise",
"=",
"Q",
".",
"makePromise",
"(",
"{",
"when",
":",
"function",
"(",
")",
"{",
"return",
"this",
";",
"}",
"}",
",",
"function",
"(",
"op",
",",
"args",
")",
"{",
"var",
"local... | makes a promise that will send all of its events to a remote object. | [
"makes",
"a",
"promise",
"that",
"will",
"send",
"all",
"of",
"its",
"events",
"to",
"a",
"remote",
"object",
"."
] | 85fad079361a1a755004ebec08e7b5fc3455a36c | https://github.com/kriskowal/q-connection/blob/85fad079361a1a755004ebec08e7b5fc3455a36c/q-connection.js#L201-L221 |
32,965 | dwyl/hapi-auth-google | lib/index.js | create_oauth2_client | function create_oauth2_client () {
var google_client_id = (OPTIONS.GOOGLE_CLIENT_ID) ? OPTIONS.GOOGLE_CLIENT_ID : process.env.GOOGLE_CLIENT_ID;
var google_client_secret = (OPTIONS.GOOGLE_CLIENT_SECRET) ? OPTIONS.GOOGLE_CLIENT_SECRET : process.env.GOOGLE_CLIENT_SECRET;
var base_url = (OPTIONS.BASE_URL) ? OPTIONS.BASE_URL : process.env.BASE_URL;
oauth2_client = new OAuth2Client(
google_client_id,
google_client_secret,
base_url + OPTIONS.REDIRECT_URL
);
return oauth2_client;
} | javascript | function create_oauth2_client () {
var google_client_id = (OPTIONS.GOOGLE_CLIENT_ID) ? OPTIONS.GOOGLE_CLIENT_ID : process.env.GOOGLE_CLIENT_ID;
var google_client_secret = (OPTIONS.GOOGLE_CLIENT_SECRET) ? OPTIONS.GOOGLE_CLIENT_SECRET : process.env.GOOGLE_CLIENT_SECRET;
var base_url = (OPTIONS.BASE_URL) ? OPTIONS.BASE_URL : process.env.BASE_URL;
oauth2_client = new OAuth2Client(
google_client_id,
google_client_secret,
base_url + OPTIONS.REDIRECT_URL
);
return oauth2_client;
} | [
"function",
"create_oauth2_client",
"(",
")",
"{",
"var",
"google_client_id",
"=",
"(",
"OPTIONS",
".",
"GOOGLE_CLIENT_ID",
")",
"?",
"OPTIONS",
".",
"GOOGLE_CLIENT_ID",
":",
"process",
".",
"env",
".",
"GOOGLE_CLIENT_ID",
";",
"var",
"google_client_secret",
"=",
... | create_oauth2_client creates the OAuth2 client
@param {Object} options - the options passed into the plugin
@returns {Object} oauth2_client - the Google OAuth2 client | [
"create_oauth2_client",
"creates",
"the",
"OAuth2",
"client"
] | 9499d49fabd673594719ae5919103a112f9eaed1 | https://github.com/dwyl/hapi-auth-google/blob/9499d49fabd673594719ae5919103a112f9eaed1/lib/index.js#L12-L22 |
32,966 | dwyl/hapi-auth-google | lib/index.js | generate_google_oauth2_url | function generate_google_oauth2_url () {
var access_type = (OPTIONS.access_type) ? OPTIONS.access_type : 'offline';
var approval_prompt = (OPTIONS.approval_prompt) ? OPTIONS.approval_prompt : 'force';
var url = oauth2_client.generateAuthUrl({
access_type: access_type, // set to offline to force a refresh token
approval_prompt: approval_prompt,
scope: OPTIONS.scope // can be a space-delimited string or array of scopes
});
return url;
} | javascript | function generate_google_oauth2_url () {
var access_type = (OPTIONS.access_type) ? OPTIONS.access_type : 'offline';
var approval_prompt = (OPTIONS.approval_prompt) ? OPTIONS.approval_prompt : 'force';
var url = oauth2_client.generateAuthUrl({
access_type: access_type, // set to offline to force a refresh token
approval_prompt: approval_prompt,
scope: OPTIONS.scope // can be a space-delimited string or array of scopes
});
return url;
} | [
"function",
"generate_google_oauth2_url",
"(",
")",
"{",
"var",
"access_type",
"=",
"(",
"OPTIONS",
".",
"access_type",
")",
"?",
"OPTIONS",
".",
"access_type",
":",
"'offline'",
";",
"var",
"approval_prompt",
"=",
"(",
"OPTIONS",
".",
"approval_prompt",
")",
... | getGoogleAuthURL creates a url where the user is sent to authenticate
no param
@returns {String} url - the url where people visit to authenticate | [
"getGoogleAuthURL",
"creates",
"a",
"url",
"where",
"the",
"user",
"is",
"sent",
"to",
"authenticate",
"no",
"param"
] | 9499d49fabd673594719ae5919103a112f9eaed1 | https://github.com/dwyl/hapi-auth-google/blob/9499d49fabd673594719ae5919103a112f9eaed1/lib/index.js#L30-L39 |
32,967 | emmetio/atom-plugin | lib/actions/balance.js | selectionRangesForHTMLNode | function selectionRangesForHTMLNode(node) {
const ranges = [new Range(node.start, node.end)];
if (node.close) {
ranges.push(new Range(node.open.end, node.close.start));
}
return ranges;
} | javascript | function selectionRangesForHTMLNode(node) {
const ranges = [new Range(node.start, node.end)];
if (node.close) {
ranges.push(new Range(node.open.end, node.close.start));
}
return ranges;
} | [
"function",
"selectionRangesForHTMLNode",
"(",
"node",
")",
"{",
"const",
"ranges",
"=",
"[",
"new",
"Range",
"(",
"node",
".",
"start",
",",
"node",
".",
"end",
")",
"]",
";",
"if",
"(",
"node",
".",
"close",
")",
"{",
"ranges",
".",
"push",
"(",
... | Returns possible selection ranges for given HTML node, from outer to inner
@param {Node} node
@return {Range[]} | [
"Returns",
"possible",
"selection",
"ranges",
"for",
"given",
"HTML",
"node",
"from",
"outer",
"to",
"inner"
] | a7b4a447647e493d1edf9df3fb901740c9fbc384 | https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/balance.js#L84-L91 |
32,968 | emmetio/atom-plugin | lib/actions/balance.js | selectionRangesForCSSNode | function selectionRangesForCSSNode(node) {
const ranges = [new Range(node.start, node.end)];
if (node.type === 'property' && node.valueToken) {
ranges.push(new Range(node.valueToken.start, node.valueToken.end));
} else if (node.type === 'rule' || node.type === 'at-rule') {
ranges.push(new Range(node.contentStartToken.end, node.contentEndToken.start));
}
return ranges;
} | javascript | function selectionRangesForCSSNode(node) {
const ranges = [new Range(node.start, node.end)];
if (node.type === 'property' && node.valueToken) {
ranges.push(new Range(node.valueToken.start, node.valueToken.end));
} else if (node.type === 'rule' || node.type === 'at-rule') {
ranges.push(new Range(node.contentStartToken.end, node.contentEndToken.start));
}
return ranges;
} | [
"function",
"selectionRangesForCSSNode",
"(",
"node",
")",
"{",
"const",
"ranges",
"=",
"[",
"new",
"Range",
"(",
"node",
".",
"start",
",",
"node",
".",
"end",
")",
"]",
";",
"if",
"(",
"node",
".",
"type",
"===",
"'property'",
"&&",
"node",
".",
"v... | Returns possible selection ranges for given CSS node, from outer to inner
@param {Node} node
@return {Range[]} | [
"Returns",
"possible",
"selection",
"ranges",
"for",
"given",
"CSS",
"node",
"from",
"outer",
"to",
"inner"
] | a7b4a447647e493d1edf9df3fb901740c9fbc384 | https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/balance.js#L98-L108 |
32,969 | running-coder/jquery-form-validation | src/jquery.validation.js | delegateDynamicValidation | function delegateDynamicValidation() {
if (!options.dynamic.settings.trigger) {
return false;
}
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'delegateDynamicValidation()',
'message': 'OK - Dynamic Validation activated on ' + node.length + ' form(s)'
});
// {/debug}
if (!node.find('[' + _data.validation + '],[' + _data.regex + ']')[0]) {
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'delegateDynamicValidation()',
'arguments': 'node.find([' + _data.validation + '],[' + _data.regex + '])',
'message': 'ERROR - [' + _data.validation + '] not found'
});
// {/debug}
return false;
}
var event = options.dynamic.settings.trigger + delegateSuffix;
if (options.dynamic.settings.trigger !== "focusout") {
event += " change" + delegateSuffix + " paste" + delegateSuffix;
}
$.each(
node.find('[' + _data.validation + '],[' + _data.regex + ']'),
function (index, input) {
$(input).unbind(event).on(event, function (e) {
if ($(this).is(':disabled')) {
return false;
}
//e.preventDefault();
var input = this,
keyCode = e.keyCode || null;
_typeWatch(function () {
if (!validateInput(input)) {
displayOneError(input.name);
_executeCallback(options.dynamic.callback.onError, [node, input, keyCode, errors[input.name]]);
} else {
_executeCallback(options.dynamic.callback.onSuccess, [node, input, keyCode]);
}
_executeCallback(options.dynamic.callback.onComplete, [node, input, keyCode]);
}, options.dynamic.settings.delay);
});
}
);
} | javascript | function delegateDynamicValidation() {
if (!options.dynamic.settings.trigger) {
return false;
}
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'delegateDynamicValidation()',
'message': 'OK - Dynamic Validation activated on ' + node.length + ' form(s)'
});
// {/debug}
if (!node.find('[' + _data.validation + '],[' + _data.regex + ']')[0]) {
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'delegateDynamicValidation()',
'arguments': 'node.find([' + _data.validation + '],[' + _data.regex + '])',
'message': 'ERROR - [' + _data.validation + '] not found'
});
// {/debug}
return false;
}
var event = options.dynamic.settings.trigger + delegateSuffix;
if (options.dynamic.settings.trigger !== "focusout") {
event += " change" + delegateSuffix + " paste" + delegateSuffix;
}
$.each(
node.find('[' + _data.validation + '],[' + _data.regex + ']'),
function (index, input) {
$(input).unbind(event).on(event, function (e) {
if ($(this).is(':disabled')) {
return false;
}
//e.preventDefault();
var input = this,
keyCode = e.keyCode || null;
_typeWatch(function () {
if (!validateInput(input)) {
displayOneError(input.name);
_executeCallback(options.dynamic.callback.onError, [node, input, keyCode, errors[input.name]]);
} else {
_executeCallback(options.dynamic.callback.onSuccess, [node, input, keyCode]);
}
_executeCallback(options.dynamic.callback.onComplete, [node, input, keyCode]);
}, options.dynamic.settings.delay);
});
}
);
} | [
"function",
"delegateDynamicValidation",
"(",
")",
"{",
"if",
"(",
"!",
"options",
".",
"dynamic",
".",
"settings",
".",
"trigger",
")",
"{",
"return",
"false",
";",
"}",
"// {debug}",
"options",
".",
"debug",
"&&",
"window",
".",
"Debug",
".",
"log",
"(... | Delegates the dynamic validation on data-validation and data-validation-regex attributes based on trigger.
@returns {Boolean} false if the option is not set | [
"Delegates",
"the",
"dynamic",
"validation",
"on",
"data",
"-",
"validation",
"and",
"data",
"-",
"validation",
"-",
"regex",
"attributes",
"based",
"on",
"trigger",
"."
] | 196540a32e6dea66f2c1c2baea078931369c26cd | https://github.com/running-coder/jquery-form-validation/blob/196540a32e6dea66f2c1c2baea078931369c26cd/src/jquery.validation.js#L321-L389 |
32,970 | running-coder/jquery-form-validation | src/jquery.validation.js | validateForm | function validateForm() {
var isValid = isEmpty(errors);
formData = {};
$.each(
node.find('input:not([type="submit"]), select, textarea').not(':disabled'),
function(index, input) {
input = $(input);
var value = _getInputValue(input[0]),
inputName = input.attr('name');
if (inputName) {
if (/\[]$/.test(inputName)) {
inputName = inputName.replace(/\[]$/, '');
if (!(formData[inputName] instanceof Array)) {
formData[inputName] = [];
}
formData[inputName].push(value)
} else {
formData[inputName] = value;
}
}
if (!!input.attr(_data.validation) || !!input.attr(_data.regex)) {
if (!validateInput(input[0], value)) {
isValid = false;
}
}
}
);
prepareFormData();
return isValid;
} | javascript | function validateForm() {
var isValid = isEmpty(errors);
formData = {};
$.each(
node.find('input:not([type="submit"]), select, textarea').not(':disabled'),
function(index, input) {
input = $(input);
var value = _getInputValue(input[0]),
inputName = input.attr('name');
if (inputName) {
if (/\[]$/.test(inputName)) {
inputName = inputName.replace(/\[]$/, '');
if (!(formData[inputName] instanceof Array)) {
formData[inputName] = [];
}
formData[inputName].push(value)
} else {
formData[inputName] = value;
}
}
if (!!input.attr(_data.validation) || !!input.attr(_data.regex)) {
if (!validateInput(input[0], value)) {
isValid = false;
}
}
}
);
prepareFormData();
return isValid;
} | [
"function",
"validateForm",
"(",
")",
"{",
"var",
"isValid",
"=",
"isEmpty",
"(",
"errors",
")",
";",
"formData",
"=",
"{",
"}",
";",
"$",
".",
"each",
"(",
"node",
".",
"find",
"(",
"'input:not([type=\"submit\"]), select, textarea'",
")",
".",
"not",
"(",... | For every "data-validation" & "data-pattern" attributes that are not disabled inside the jQuery "node" object
the "validateInput" function will be called.
@returns {Boolean} true if no error(s) were found (valid form) | [
"For",
"every",
"data",
"-",
"validation",
"&",
"data",
"-",
"pattern",
"attributes",
"that",
"are",
"not",
"disabled",
"inside",
"the",
"jQuery",
"node",
"object",
"the",
"validateInput",
"function",
"will",
"be",
"called",
"."
] | 196540a32e6dea66f2c1c2baea078931369c26cd | https://github.com/running-coder/jquery-form-validation/blob/196540a32e6dea66f2c1c2baea078931369c26cd/src/jquery.validation.js#L470-L509 |
32,971 | running-coder/jquery-form-validation | src/jquery.validation.js | prepareFormData | function prepareFormData() {
var data = {},
matches,
index;
for (var i in formData) {
if (!formData.hasOwnProperty(i)) continue;
index = 0;
matches = i.split(/\[(.+?)]/g);
var tmpObject = {},
tmpArray = [];
for (var k = matches.length - 1; k >= 0; k--) {
if (matches[k] === "") {
matches.splice(k, 1);
continue;
}
if (tmpArray.length < 1) {
tmpObject[matches[k]] = Number(formData[i]) || formData[i];
} else {
tmpObject = {};
tmpObject[matches[k]] = tmpArray[tmpArray.length - 1];
}
tmpArray.push(tmpObject)
}
data = $.extend(true, data, tmpObject);
}
formData = data;
} | javascript | function prepareFormData() {
var data = {},
matches,
index;
for (var i in formData) {
if (!formData.hasOwnProperty(i)) continue;
index = 0;
matches = i.split(/\[(.+?)]/g);
var tmpObject = {},
tmpArray = [];
for (var k = matches.length - 1; k >= 0; k--) {
if (matches[k] === "") {
matches.splice(k, 1);
continue;
}
if (tmpArray.length < 1) {
tmpObject[matches[k]] = Number(formData[i]) || formData[i];
} else {
tmpObject = {};
tmpObject[matches[k]] = tmpArray[tmpArray.length - 1];
}
tmpArray.push(tmpObject)
}
data = $.extend(true, data, tmpObject);
}
formData = data;
} | [
"function",
"prepareFormData",
"(",
")",
"{",
"var",
"data",
"=",
"{",
"}",
",",
"matches",
",",
"index",
";",
"for",
"(",
"var",
"i",
"in",
"formData",
")",
"{",
"if",
"(",
"!",
"formData",
".",
"hasOwnProperty",
"(",
"i",
")",
")",
"continue",
";... | Loop through formData and build an object
@returns {Object} data | [
"Loop",
"through",
"formData",
"and",
"build",
"an",
"object"
] | 196540a32e6dea66f2c1c2baea078931369c26cd | https://github.com/running-coder/jquery-form-validation/blob/196540a32e6dea66f2c1c2baea078931369c26cd/src/jquery.validation.js#L516-L553 |
32,972 | running-coder/jquery-form-validation | src/jquery.validation.js | validateInput | function validateInput(input, value) {
var inputName = $(input).attr('name'),
value = value || _getInputValue(input);
if (!inputName) {
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'validateInput()',
'arguments': '$(input).attr("name")',
'message': 'ERROR - Missing input [name]'
});
// {/debug}
return false;
}
var matches = inputName.replace(/]$/, '').split(/]\[|[[\]]/g),
inputShortName = window.Validation.labels[inputName] ||
options.labels[inputName] ||
$(input).attr(_data.label) ||
matches[matches.length - 1],
validationArray = $(input).attr(_data.validation),
validationMessage = $(input).attr(_data.validationMessage),
validationRegex = $(input).attr(_data.regex),
validationRegexReverse = !($(input).attr(_data.regexReverse) === undefined),
validationRegexMessage = $(input).attr(_data.regexMessage),
validateOnce = false;
if (validationArray) {
validationArray = _api._splitValidation(validationArray);
}
// Validates the "data-validation"
if (validationArray instanceof Array && validationArray.length > 0) {
// "OPTIONAL" input will not be validated if it's empty
if ($.trim(value) === '' && ~validationArray.indexOf('OPTIONAL')) {
return true;
}
$.each(validationArray, function (i, rule) {
if (validateOnce === true) {
return true;
}
try {
validateRule(value, rule);
} catch (error) {
if (validationMessage || !options.submit.settings.allErrors) {
validateOnce = true;
}
error[0] = validationMessage || error[0];
registerError(inputName, error[0].replace('$', inputShortName).replace('%', error[1]));
}
});
}
// Validates the "data-validation-regex"
if (validationRegex) {
var rule = _buildRegexFromString(validationRegex);
// Do not block validation if a regexp is bad, only skip it
if (!(rule instanceof RegExp)) {
return true;
}
try {
validateRule(value, rule, validationRegexReverse);
} catch (error) {
error[0] = validationRegexMessage || error[0];
registerError(inputName, error[0].replace('$', inputShortName));
}
}
return !errors[inputName] || errors[inputName] instanceof Array && errors[inputName].length === 0;
} | javascript | function validateInput(input, value) {
var inputName = $(input).attr('name'),
value = value || _getInputValue(input);
if (!inputName) {
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'validateInput()',
'arguments': '$(input).attr("name")',
'message': 'ERROR - Missing input [name]'
});
// {/debug}
return false;
}
var matches = inputName.replace(/]$/, '').split(/]\[|[[\]]/g),
inputShortName = window.Validation.labels[inputName] ||
options.labels[inputName] ||
$(input).attr(_data.label) ||
matches[matches.length - 1],
validationArray = $(input).attr(_data.validation),
validationMessage = $(input).attr(_data.validationMessage),
validationRegex = $(input).attr(_data.regex),
validationRegexReverse = !($(input).attr(_data.regexReverse) === undefined),
validationRegexMessage = $(input).attr(_data.regexMessage),
validateOnce = false;
if (validationArray) {
validationArray = _api._splitValidation(validationArray);
}
// Validates the "data-validation"
if (validationArray instanceof Array && validationArray.length > 0) {
// "OPTIONAL" input will not be validated if it's empty
if ($.trim(value) === '' && ~validationArray.indexOf('OPTIONAL')) {
return true;
}
$.each(validationArray, function (i, rule) {
if (validateOnce === true) {
return true;
}
try {
validateRule(value, rule);
} catch (error) {
if (validationMessage || !options.submit.settings.allErrors) {
validateOnce = true;
}
error[0] = validationMessage || error[0];
registerError(inputName, error[0].replace('$', inputShortName).replace('%', error[1]));
}
});
}
// Validates the "data-validation-regex"
if (validationRegex) {
var rule = _buildRegexFromString(validationRegex);
// Do not block validation if a regexp is bad, only skip it
if (!(rule instanceof RegExp)) {
return true;
}
try {
validateRule(value, rule, validationRegexReverse);
} catch (error) {
error[0] = validationRegexMessage || error[0];
registerError(inputName, error[0].replace('$', inputShortName));
}
}
return !errors[inputName] || errors[inputName] instanceof Array && errors[inputName].length === 0;
} | [
"function",
"validateInput",
"(",
"input",
",",
"value",
")",
"{",
"var",
"inputName",
"=",
"$",
"(",
"input",
")",
".",
"attr",
"(",
"'name'",
")",
",",
"value",
"=",
"value",
"||",
"_getInputValue",
"(",
"input",
")",
";",
"if",
"(",
"!",
"inputNam... | Prepare the information from the data attributes
and call the "validateRule" function.
@param {Object} input Reference of the input element
@returns {Boolean} true if no error(s) were found (valid input) | [
"Prepare",
"the",
"information",
"from",
"the",
"data",
"attributes",
"and",
"call",
"the",
"validateRule",
"function",
"."
] | 196540a32e6dea66f2c1c2baea078931369c26cd | https://github.com/running-coder/jquery-form-validation/blob/196540a32e6dea66f2c1c2baea078931369c26cd/src/jquery.validation.js#L563-L660 |
32,973 | running-coder/jquery-form-validation | src/jquery.validation.js | validateRule | function validateRule(value, rule, reversed) {
// Validate for "data-validation-regex" and "data-validation-regex-reverse"
if (rule instanceof RegExp) {
var isValid = rule.test(value);
if (reversed) {
isValid = !isValid;
}
if (!isValid) {
throw [options.messages['default'], ''];
}
return;
}
if (options.rules[rule]) {
if (!options.rules[rule].test(value)) {
throw [options.messages[rule], ''];
}
return;
}
// Validate for comparison "data-validation"
var comparison = rule.match(options.rules.COMPARISON);
if (!comparison || comparison.length !== 4) {
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'validateRule()',
'arguments': 'value: ' + value + ' rule: ' + rule,
'message': 'WARNING - Invalid comparison'
});
// {/debug}
return;
}
var type = comparison[1],
operator = comparison[2],
compared = comparison[3],
comparedValue;
switch (type) {
// Compare input "Length"
case "L":
// Only numeric value for "L" are allowed
if (isNaN(compared)) {
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'validateRule()',
'arguments': 'compare: ' + compared + ' rule: ' + rule,
'message': 'WARNING - Invalid rule, "L" compare must be numeric'
});
// {/debug}
return false;
} else {
if (!value || eval(value.length + operator + parseFloat(compared)) === false) {
throw [options.messages[operator], compared];
}
}
break;
// Compare input "Value"
case "V":
default:
// Compare Field values
if (isNaN(compared)) {
comparedValue = node.find('[name="' + compared + '"]').val();
if (!comparedValue) {
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'validateRule()',
'arguments': 'compare: ' + compared + ' rule: ' + rule,
'message': 'WARNING - Unable to find compared field [name="' + compared + '"]'
});
// {/debug}
return false;
}
if (!value || !eval('"' + encodeURIComponent(value) + '"' + operator + '"' + encodeURIComponent(comparedValue) + '"')) {
throw [options.messages[operator].replace(' characters', ''), compared];
}
} else {
// Compare numeric value
if (!value || isNaN(value) || !eval(value + operator + parseFloat(compared))) {
throw [options.messages[operator].replace(' characters', ''), compared];
}
}
break;
}
} | javascript | function validateRule(value, rule, reversed) {
// Validate for "data-validation-regex" and "data-validation-regex-reverse"
if (rule instanceof RegExp) {
var isValid = rule.test(value);
if (reversed) {
isValid = !isValid;
}
if (!isValid) {
throw [options.messages['default'], ''];
}
return;
}
if (options.rules[rule]) {
if (!options.rules[rule].test(value)) {
throw [options.messages[rule], ''];
}
return;
}
// Validate for comparison "data-validation"
var comparison = rule.match(options.rules.COMPARISON);
if (!comparison || comparison.length !== 4) {
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'validateRule()',
'arguments': 'value: ' + value + ' rule: ' + rule,
'message': 'WARNING - Invalid comparison'
});
// {/debug}
return;
}
var type = comparison[1],
operator = comparison[2],
compared = comparison[3],
comparedValue;
switch (type) {
// Compare input "Length"
case "L":
// Only numeric value for "L" are allowed
if (isNaN(compared)) {
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'validateRule()',
'arguments': 'compare: ' + compared + ' rule: ' + rule,
'message': 'WARNING - Invalid rule, "L" compare must be numeric'
});
// {/debug}
return false;
} else {
if (!value || eval(value.length + operator + parseFloat(compared)) === false) {
throw [options.messages[operator], compared];
}
}
break;
// Compare input "Value"
case "V":
default:
// Compare Field values
if (isNaN(compared)) {
comparedValue = node.find('[name="' + compared + '"]').val();
if (!comparedValue) {
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'validateRule()',
'arguments': 'compare: ' + compared + ' rule: ' + rule,
'message': 'WARNING - Unable to find compared field [name="' + compared + '"]'
});
// {/debug}
return false;
}
if (!value || !eval('"' + encodeURIComponent(value) + '"' + operator + '"' + encodeURIComponent(comparedValue) + '"')) {
throw [options.messages[operator].replace(' characters', ''), compared];
}
} else {
// Compare numeric value
if (!value || isNaN(value) || !eval(value + operator + parseFloat(compared))) {
throw [options.messages[operator].replace(' characters', ''), compared];
}
}
break;
}
} | [
"function",
"validateRule",
"(",
"value",
",",
"rule",
",",
"reversed",
")",
"{",
"// Validate for \"data-validation-regex\" and \"data-validation-regex-reverse\"",
"if",
"(",
"rule",
"instanceof",
"RegExp",
")",
"{",
"var",
"isValid",
"=",
"rule",
".",
"test",
"(",
... | Validate an input value against one rule.
If a "value-rule" mismatch occurs, an error is thrown to the caller function.
@param {String} value
@param {*} rule
@param {Boolean} [reversed]
@returns {*} Error if a mismatch occurred. | [
"Validate",
"an",
"input",
"value",
"against",
"one",
"rule",
".",
"If",
"a",
"value",
"-",
"rule",
"mismatch",
"occurs",
"an",
"error",
"is",
"thrown",
"to",
"the",
"caller",
"function",
"."
] | 196540a32e6dea66f2c1c2baea078931369c26cd | https://github.com/running-coder/jquery-form-validation/blob/196540a32e6dea66f2c1c2baea078931369c26cd/src/jquery.validation.js#L672-L783 |
32,974 | running-coder/jquery-form-validation | src/jquery.validation.js | registerError | function registerError(inputName, error) {
if (!errors[inputName]) {
errors[inputName] = [];
}
error = error.capitalize();
var hasError = false;
for (var i = 0; i < errors[inputName].length; i++) {
if (errors[inputName][i] === error) {
hasError = true;
break;
}
}
if (!hasError) {
errors[inputName].push(error);
}
} | javascript | function registerError(inputName, error) {
if (!errors[inputName]) {
errors[inputName] = [];
}
error = error.capitalize();
var hasError = false;
for (var i = 0; i < errors[inputName].length; i++) {
if (errors[inputName][i] === error) {
hasError = true;
break;
}
}
if (!hasError) {
errors[inputName].push(error);
}
} | [
"function",
"registerError",
"(",
"inputName",
",",
"error",
")",
"{",
"if",
"(",
"!",
"errors",
"[",
"inputName",
"]",
")",
"{",
"errors",
"[",
"inputName",
"]",
"=",
"[",
"]",
";",
"}",
"error",
"=",
"error",
".",
"capitalize",
"(",
")",
";",
"va... | Register an error into the global "error" variable.
@param {String} inputName Input where the error occurred
@param {String} error Description of the error to be displayed | [
"Register",
"an",
"error",
"into",
"the",
"global",
"error",
"variable",
"."
] | 196540a32e6dea66f2c1c2baea078931369c26cd | https://github.com/running-coder/jquery-form-validation/blob/196540a32e6dea66f2c1c2baea078931369c26cd/src/jquery.validation.js#L791-L811 |
32,975 | running-coder/jquery-form-validation | src/jquery.validation.js | resetOneError | function resetOneError(inputName, input, label, container, group) {
delete errors[inputName];
if (container) {
//window.Validation.hasScrolled = false;
if (options.submit.settings.inputContainer) {
(group ? label : input).parentsUntil(node, options.submit.settings.inputContainer).removeClass(options.submit.settings.errorClass);
}
label && label.removeClass(options.submit.settings.errorClass);
input.removeClass(options.submit.settings.errorClass);
if (options.submit.settings.display === 'inline') {
container.find('[' + _data.errorList + ']').remove();
}
} else {
if (!input) {
input = node.find('[name="' + inputName + '"]');
if (!input[0]) {
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'resetOneError()',
'arguments': '[name="' + inputName + '"]',
'message': 'ERROR - Unable to find input by name "' + inputName + '"'
});
// {/debug}
return false;
}
}
input.trigger('coucou' + resetSuffix);
}
} | javascript | function resetOneError(inputName, input, label, container, group) {
delete errors[inputName];
if (container) {
//window.Validation.hasScrolled = false;
if (options.submit.settings.inputContainer) {
(group ? label : input).parentsUntil(node, options.submit.settings.inputContainer).removeClass(options.submit.settings.errorClass);
}
label && label.removeClass(options.submit.settings.errorClass);
input.removeClass(options.submit.settings.errorClass);
if (options.submit.settings.display === 'inline') {
container.find('[' + _data.errorList + ']').remove();
}
} else {
if (!input) {
input = node.find('[name="' + inputName + '"]');
if (!input[0]) {
// {debug}
options.debug && window.Debug.log({
'node': node,
'function': 'resetOneError()',
'arguments': '[name="' + inputName + '"]',
'message': 'ERROR - Unable to find input by name "' + inputName + '"'
});
// {/debug}
return false;
}
}
input.trigger('coucou' + resetSuffix);
}
} | [
"function",
"resetOneError",
"(",
"inputName",
",",
"input",
",",
"label",
",",
"container",
",",
"group",
")",
"{",
"delete",
"errors",
"[",
"inputName",
"]",
";",
"if",
"(",
"container",
")",
"{",
"//window.Validation.hasScrolled = false;",
"if",
"(",
"optio... | Remove an input error.
@param {String} inputName Key reference to delete the error from "errors" global variable
@param {Object} input jQuery object of the input
@param {Object} label jQuery object of the input's label
@param {Object} container jQuery object of the "errorList"
@param {String} [group] Name of the group if any (ex: used on input radio) | [
"Remove",
"an",
"input",
"error",
"."
] | 196540a32e6dea66f2c1c2baea078931369c26cd | https://github.com/running-coder/jquery-form-validation/blob/196540a32e6dea66f2c1c2baea078931369c26cd/src/jquery.validation.js#L998-L1041 |
32,976 | running-coder/jquery-form-validation | src/jquery.validation.js | destroy | function destroy() {
resetErrors();
node.find('[' + _data.validation + '],[' + _data.regex + ']').off(delegateSuffix + ' ' + resetSuffix);
node.find(options.submit.settings.button).off(delegateSuffix).on('click' + delegateSuffix, function () {
$(this).closest('form')[0].submit();
});
//delete window.Validation.form[node.selector];
return true;
} | javascript | function destroy() {
resetErrors();
node.find('[' + _data.validation + '],[' + _data.regex + ']').off(delegateSuffix + ' ' + resetSuffix);
node.find(options.submit.settings.button).off(delegateSuffix).on('click' + delegateSuffix, function () {
$(this).closest('form')[0].submit();
});
//delete window.Validation.form[node.selector];
return true;
} | [
"function",
"destroy",
"(",
")",
"{",
"resetErrors",
"(",
")",
";",
"node",
".",
"find",
"(",
"'['",
"+",
"_data",
".",
"validation",
"+",
"'],['",
"+",
"_data",
".",
"regex",
"+",
"']'",
")",
".",
"off",
"(",
"delegateSuffix",
"+",
"' '",
"+",
"re... | Destroy the Validation instance
@returns {Boolean} | [
"Destroy",
"the",
"Validation",
"instance"
] | 196540a32e6dea66f2c1c2baea078931369c26cd | https://github.com/running-coder/jquery-form-validation/blob/196540a32e6dea66f2c1c2baea078931369c26cd/src/jquery.validation.js#L1073-L1086 |
32,977 | running-coder/jquery-form-validation | src/jquery.validation.js | function (node, validation) {
var self = this;
validation = self._splitValidation(validation);
if (!validation) {
return false;
}
return node.each(function () {
var $this = $(this),
validationData = $this.attr(_data.validation),
validationArray = (validationData && validationData.length) ? self._splitValidation(validationData) : [],
oneValidation,
validationIndex;
if (!validationArray.length) {
$this.removeAttr(_data.validation);
return true;
}
for (var i = 0; i < validation.length; i++) {
oneValidation = self._formatValidation(validation[i]);
validationIndex = $.inArray(oneValidation, validationArray);
if (validationIndex !== -1) {
validationArray.splice(validationIndex, 1);
}
}
if (!validationArray.length) {
$this.removeAttr(_data.validation);
return true;
}
$this.attr(_data.validation, self._joinValidation(validationArray));
});
} | javascript | function (node, validation) {
var self = this;
validation = self._splitValidation(validation);
if (!validation) {
return false;
}
return node.each(function () {
var $this = $(this),
validationData = $this.attr(_data.validation),
validationArray = (validationData && validationData.length) ? self._splitValidation(validationData) : [],
oneValidation,
validationIndex;
if (!validationArray.length) {
$this.removeAttr(_data.validation);
return true;
}
for (var i = 0; i < validation.length; i++) {
oneValidation = self._formatValidation(validation[i]);
validationIndex = $.inArray(oneValidation, validationArray);
if (validationIndex !== -1) {
validationArray.splice(validationIndex, 1);
}
}
if (!validationArray.length) {
$this.removeAttr(_data.validation);
return true;
}
$this.attr(_data.validation, self._joinValidation(validationArray));
});
} | [
"function",
"(",
"node",
",",
"validation",
")",
"{",
"var",
"self",
"=",
"this",
";",
"validation",
"=",
"self",
".",
"_splitValidation",
"(",
"validation",
")",
";",
"if",
"(",
"!",
"validation",
")",
"{",
"return",
"false",
";",
"}",
"return",
"node... | API method to handle the removal of "data-validation" arguments.
@param {Object} node jQuery objects
@param {String|Array} validation arguments to remove in the node(s) "data-validation"
@returns {*} | [
"API",
"method",
"to",
"handle",
"the",
"removal",
"of",
"data",
"-",
"validation",
"arguments",
"."
] | 196540a32e6dea66f2c1c2baea078931369c26cd | https://github.com/running-coder/jquery-form-validation/blob/196540a32e6dea66f2c1c2baea078931369c26cd/src/jquery.validation.js#L1598-L1638 | |
32,978 | running-coder/jquery-form-validation | src/jquery.validation.js | function (ruleObj) {
if (!ruleObj.rule || (!ruleObj.regex && !ruleObj.message)) {
// {debug}
window.Debug.log({
'function': '$.alterValidationRules()',
'message': 'ERROR - Missing one or multiple parameter(s) {rule, regex, message}'
});
window.Debug.print();
// {/debug}
return false;
}
ruleObj.rule = ruleObj.rule.toUpperCase();
if (ruleObj.regex) {
var regex = _buildRegexFromString(ruleObj.regex);
if (!(regex instanceof RegExp)) {
// {debug}
window.Debug.log({
'function': '$.alterValidationRules(rule)',
'arguments': regex.toString(),
'message': 'ERROR - Invalid rule'
});
window.Debug.print();
// {/debug}
return false;
}
_rules[ruleObj.rule] = regex;
}
if (ruleObj.message) {
_messages[ruleObj.rule] = ruleObj.message;
}
return true;
} | javascript | function (ruleObj) {
if (!ruleObj.rule || (!ruleObj.regex && !ruleObj.message)) {
// {debug}
window.Debug.log({
'function': '$.alterValidationRules()',
'message': 'ERROR - Missing one or multiple parameter(s) {rule, regex, message}'
});
window.Debug.print();
// {/debug}
return false;
}
ruleObj.rule = ruleObj.rule.toUpperCase();
if (ruleObj.regex) {
var regex = _buildRegexFromString(ruleObj.regex);
if (!(regex instanceof RegExp)) {
// {debug}
window.Debug.log({
'function': '$.alterValidationRules(rule)',
'arguments': regex.toString(),
'message': 'ERROR - Invalid rule'
});
window.Debug.print();
// {/debug}
return false;
}
_rules[ruleObj.rule] = regex;
}
if (ruleObj.message) {
_messages[ruleObj.rule] = ruleObj.message;
}
return true;
} | [
"function",
"(",
"ruleObj",
")",
"{",
"if",
"(",
"!",
"ruleObj",
".",
"rule",
"||",
"(",
"!",
"ruleObj",
".",
"regex",
"&&",
"!",
"ruleObj",
".",
"message",
")",
")",
"{",
"// {debug}",
"window",
".",
"Debug",
".",
"log",
"(",
"{",
"'function'",
":... | API method to add a validation rule.
@example
$.alterValidationRules({
rule: 'FILENAME',
regex: /^[^\\/:\*\?<>\|\"\']*$/,
message: '$ has an invalid filename.'
})
@param {Object} ruleObj | [
"API",
"method",
"to",
"add",
"a",
"validation",
"rule",
"."
] | 196540a32e6dea66f2c1c2baea078931369c26cd | https://github.com/running-coder/jquery-form-validation/blob/196540a32e6dea66f2c1c2baea078931369c26cd/src/jquery.validation.js#L1852-L1891 | |
32,979 | emmetio/atom-plugin | lib/actions/remove-tag.js | findNextNonSpacePoint | function findNextNonSpacePoint(editor, pos) {
const stream = new BufferStreamReader(editor.getBuffer(), pos);
stream.eatWhile(isSpace);
return stream.pos;
} | javascript | function findNextNonSpacePoint(editor, pos) {
const stream = new BufferStreamReader(editor.getBuffer(), pos);
stream.eatWhile(isSpace);
return stream.pos;
} | [
"function",
"findNextNonSpacePoint",
"(",
"editor",
",",
"pos",
")",
"{",
"const",
"stream",
"=",
"new",
"BufferStreamReader",
"(",
"editor",
".",
"getBuffer",
"(",
")",
",",
"pos",
")",
";",
"stream",
".",
"eatWhile",
"(",
"isSpace",
")",
";",
"return",
... | Finds position of first non-space character next to given `pos`
@param {TextEditor} editor
@param {Point} pos
@return {Point} | [
"Finds",
"position",
"of",
"first",
"non",
"-",
"space",
"character",
"next",
"to",
"given",
"pos"
] | a7b4a447647e493d1edf9df3fb901740c9fbc384 | https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/remove-tag.js#L67-L71 |
32,980 | emmetio/atom-plugin | lib/actions/remove-tag.js | findPreviousNonSpacePoint | function findPreviousNonSpacePoint(editor, pos) {
const stream = new BufferStreamReader(editor.getBuffer(), pos);
while (!stream.sof()) {
if (!isSpace(stream.backUp(1))) {
stream.next();
break;
}
}
return stream.pos;
} | javascript | function findPreviousNonSpacePoint(editor, pos) {
const stream = new BufferStreamReader(editor.getBuffer(), pos);
while (!stream.sof()) {
if (!isSpace(stream.backUp(1))) {
stream.next();
break;
}
}
return stream.pos;
} | [
"function",
"findPreviousNonSpacePoint",
"(",
"editor",
",",
"pos",
")",
"{",
"const",
"stream",
"=",
"new",
"BufferStreamReader",
"(",
"editor",
".",
"getBuffer",
"(",
")",
",",
"pos",
")",
";",
"while",
"(",
"!",
"stream",
".",
"sof",
"(",
")",
")",
... | Finds position of first non-space character that precedes given `pos`
@param {TextEditor} editor
@param {Point} pos
@return {Point} | [
"Finds",
"position",
"of",
"first",
"non",
"-",
"space",
"character",
"that",
"precedes",
"given",
"pos"
] | a7b4a447647e493d1edf9df3fb901740c9fbc384 | https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/remove-tag.js#L79-L89 |
32,981 | emmetio/atom-plugin | lib/actions/split-join-tag.js | joinTag | function joinTag(editor, node, syntax) {
// Remove everything between the end of opening tag and the end of closing tag
const open = getText(editor, node.open);
const m = open.match(/\s*>$/);
const start = node.open.end.translate([0, m ? -m[0].length : 0]);
editor.setTextInBufferRange(new Range(start, node.end),
selfClosingStyle[syntax] || selfClosingStyle.xhtml);
} | javascript | function joinTag(editor, node, syntax) {
// Remove everything between the end of opening tag and the end of closing tag
const open = getText(editor, node.open);
const m = open.match(/\s*>$/);
const start = node.open.end.translate([0, m ? -m[0].length : 0]);
editor.setTextInBufferRange(new Range(start, node.end),
selfClosingStyle[syntax] || selfClosingStyle.xhtml);
} | [
"function",
"joinTag",
"(",
"editor",
",",
"node",
",",
"syntax",
")",
"{",
"// Remove everything between the end of opening tag and the end of closing tag",
"const",
"open",
"=",
"getText",
"(",
"editor",
",",
"node",
".",
"open",
")",
";",
"const",
"m",
"=",
"op... | Joins given tag into single, unary tag
@param {TextEditor} editor
@param {Node} node
@param {String} syntax Host document syntax, defines how self-closing tag
should be displayed | [
"Joins",
"given",
"tag",
"into",
"single",
"unary",
"tag"
] | a7b4a447647e493d1edf9df3fb901740c9fbc384 | https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/split-join-tag.js#L65-L72 |
32,982 | emmetio/atom-plugin | lib/actions/toggle-block-comment.js | comment | function comment(editor, range, modelType) {
const commentParts = modelComments[modelType];
editor.setTextInBufferRange(new Range(range.end, range.end), ` ${commentParts.after}`);
editor.setTextInBufferRange(new Range(range.start, range.start), `${commentParts.before} `);
} | javascript | function comment(editor, range, modelType) {
const commentParts = modelComments[modelType];
editor.setTextInBufferRange(new Range(range.end, range.end), ` ${commentParts.after}`);
editor.setTextInBufferRange(new Range(range.start, range.start), `${commentParts.before} `);
} | [
"function",
"comment",
"(",
"editor",
",",
"range",
",",
"modelType",
")",
"{",
"const",
"commentParts",
"=",
"modelComments",
"[",
"modelType",
"]",
";",
"editor",
".",
"setTextInBufferRange",
"(",
"new",
"Range",
"(",
"range",
".",
"end",
",",
"range",
"... | Comments given node in text editor
@param {TextEditor} editor
@param {Range} range
@param {String} modelType | [
"Comments",
"given",
"node",
"in",
"text",
"editor"
] | a7b4a447647e493d1edf9df3fb901740c9fbc384 | https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/toggle-block-comment.js#L73-L77 |
32,983 | emmetio/atom-plugin | lib/actions/toggle-block-comment.js | uncomment | function uncomment(editor, range, modelType) {
const commentParts = modelComments[modelType];
const stream = new BufferStreamReader(editor.getBuffer(), range.start, range);
// narrow down comment range till meanful content
stream.pos = range.start.translate([0, commentParts.before.length]);
stream.eatWhile(isSpace);
stream.start = stream.pos;
// Make sure comment ends with proper token
stream.pos = range.end.translate([0, -commentParts.after.length]);
if (editor.getTextInBufferRange([stream.pos, range.end]) === commentParts.after) {
while (!stream.sof()) {
if (!isSpace(stream.backUp(1))) {
stream.next();
break;
}
}
} else {
stream.pos = range.end;
}
const start = new Range(range.start, stream.start);
const end = new Range(stream.pos, range.end);
const delta = {
start: editor.getTextInBufferRange(start).length,
end: editor.getTextInBufferRange(end).length
};
editor.setTextInBufferRange(end, '');
editor.setTextInBufferRange(start, '');
return delta;
} | javascript | function uncomment(editor, range, modelType) {
const commentParts = modelComments[modelType];
const stream = new BufferStreamReader(editor.getBuffer(), range.start, range);
// narrow down comment range till meanful content
stream.pos = range.start.translate([0, commentParts.before.length]);
stream.eatWhile(isSpace);
stream.start = stream.pos;
// Make sure comment ends with proper token
stream.pos = range.end.translate([0, -commentParts.after.length]);
if (editor.getTextInBufferRange([stream.pos, range.end]) === commentParts.after) {
while (!stream.sof()) {
if (!isSpace(stream.backUp(1))) {
stream.next();
break;
}
}
} else {
stream.pos = range.end;
}
const start = new Range(range.start, stream.start);
const end = new Range(stream.pos, range.end);
const delta = {
start: editor.getTextInBufferRange(start).length,
end: editor.getTextInBufferRange(end).length
};
editor.setTextInBufferRange(end, '');
editor.setTextInBufferRange(start, '');
return delta;
} | [
"function",
"uncomment",
"(",
"editor",
",",
"range",
",",
"modelType",
")",
"{",
"const",
"commentParts",
"=",
"modelComments",
"[",
"modelType",
"]",
";",
"const",
"stream",
"=",
"new",
"BufferStreamReader",
"(",
"editor",
".",
"getBuffer",
"(",
")",
",",
... | Un-comments given range in text editor
@param {TextEditor} editor
@param {Range} range
@param {String} modelType
@return {Object} Returns delta of removed characters from | [
"Un",
"-",
"comments",
"given",
"range",
"in",
"text",
"editor"
] | a7b4a447647e493d1edf9df3fb901740c9fbc384 | https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/toggle-block-comment.js#L86-L119 |
32,984 | emmetio/atom-plugin | lib/actions/toggle-block-comment.js | commentsInRange | function commentsInRange(model, range) {
const intersects = token => getRange(token).intersectsWith(range, true);
if (model.type === 'html') {
// in html model, comments are nodes in model
return iterate(model.dom, node => node.type === 'comment' && intersects(node));
}
if (model.type === 'stylesheet') {
// in stylesheet model, comments are stored as separate tokens, they
// can’t be a part of model since they might be a part of selector or
// property value
return model.dom.comments.filter(intersects);
}
return [];
} | javascript | function commentsInRange(model, range) {
const intersects = token => getRange(token).intersectsWith(range, true);
if (model.type === 'html') {
// in html model, comments are nodes in model
return iterate(model.dom, node => node.type === 'comment' && intersects(node));
}
if (model.type === 'stylesheet') {
// in stylesheet model, comments are stored as separate tokens, they
// can’t be a part of model since they might be a part of selector or
// property value
return model.dom.comments.filter(intersects);
}
return [];
} | [
"function",
"commentsInRange",
"(",
"model",
",",
"range",
")",
"{",
"const",
"intersects",
"=",
"token",
"=>",
"getRange",
"(",
"token",
")",
".",
"intersectsWith",
"(",
"range",
",",
"true",
")",
";",
"if",
"(",
"model",
".",
"type",
"===",
"'html'",
... | Finds all comment ranges that matches given range
@param {SyntaxModel} model
@param {Range} range
@return {Range[]} | [
"Finds",
"all",
"comment",
"ranges",
"that",
"matches",
"given",
"range"
] | a7b4a447647e493d1edf9df3fb901740c9fbc384 | https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/toggle-block-comment.js#L148-L164 |
32,985 | emmetio/atom-plugin | lib/locate-file.js | resolveRelative | function resolveRelative(base, filePath) {
return getBasePath(base)
.then(basePath => tryFile(path.resolve(basePath, filePath)));
} | javascript | function resolveRelative(base, filePath) {
return getBasePath(base)
.then(basePath => tryFile(path.resolve(basePath, filePath)));
} | [
"function",
"resolveRelative",
"(",
"base",
",",
"filePath",
")",
"{",
"return",
"getBasePath",
"(",
"base",
")",
".",
"then",
"(",
"basePath",
"=>",
"tryFile",
"(",
"path",
".",
"resolve",
"(",
"basePath",
",",
"filePath",
")",
")",
")",
";",
"}"
] | Resolves relative file path
@param {TextEditor|String} base
@param {String} filePath
@return {Promise} | [
"Resolves",
"relative",
"file",
"path"
] | a7b4a447647e493d1edf9df3fb901740c9fbc384 | https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/locate-file.js#L35-L38 |
32,986 | emmetio/atom-plugin | lib/locate-file.js | getBasePath | function getBasePath(base) {
return new Promise((resolve, reject) => {
if (base && typeof base.getPath === 'function') {
const editorFile = base.getPath();
if (!editorFile) {
return reject(new Error('Unable to get base path: editor contains unsaved file'));
}
base = path.dirname(editorFile);
}
if (!base || typeof base !== 'string') {
reject(new Error(`Unable to get base path from ${base}`));
} else {
resolve(base);
}
});
} | javascript | function getBasePath(base) {
return new Promise((resolve, reject) => {
if (base && typeof base.getPath === 'function') {
const editorFile = base.getPath();
if (!editorFile) {
return reject(new Error('Unable to get base path: editor contains unsaved file'));
}
base = path.dirname(editorFile);
}
if (!base || typeof base !== 'string') {
reject(new Error(`Unable to get base path from ${base}`));
} else {
resolve(base);
}
});
} | [
"function",
"getBasePath",
"(",
"base",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"if",
"(",
"base",
"&&",
"typeof",
"base",
".",
"getPath",
"===",
"'function'",
")",
"{",
"const",
"editorFile",
"=",
"bas... | Returns base path from file, opened in given editor
@param {TextEditor|String} base
@return {Promise} | [
"Returns",
"base",
"path",
"from",
"file",
"opened",
"in",
"given",
"editor"
] | a7b4a447647e493d1edf9df3fb901740c9fbc384 | https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/locate-file.js#L73-L90 |
32,987 | helpers/handlebars-utils | index.js | isEmpty | function isEmpty(val) {
if (val === 0 || typeof val === 'boolean') {
return false;
}
if (val == null) {
return true;
}
if (utils.isObject(val)) {
val = Object.keys(val);
}
if (!val.length) {
return true;
}
return false;
} | javascript | function isEmpty(val) {
if (val === 0 || typeof val === 'boolean') {
return false;
}
if (val == null) {
return true;
}
if (utils.isObject(val)) {
val = Object.keys(val);
}
if (!val.length) {
return true;
}
return false;
} | [
"function",
"isEmpty",
"(",
"val",
")",
"{",
"if",
"(",
"val",
"===",
"0",
"||",
"typeof",
"val",
"===",
"'boolean'",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"val",
"==",
"null",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"utils",... | Returns true if the given value is "empty".
```js
console.log(utils.isEmpty(0));
//=> false
console.log(utils.isEmpty(''));
//=> true
console.log(utils.isEmpty([]));
//=> true
console.log(utils.isEmpty({}));
//=> true
```
@name .isEmpty
@param {any} `value`
@return {Boolean}
@api public | [
"Returns",
"true",
"if",
"the",
"given",
"value",
"is",
"empty",
"."
] | 846541474dec1aea9a405675c7809a30aa5a4072 | https://github.com/helpers/handlebars-utils/blob/846541474dec1aea9a405675c7809a30aa5a4072/index.js#L421-L435 |
32,988 | emmetio/atom-plugin | lib/image-size.js | getImageSizeFromFile | function getImageSizeFromFile(file) {
return new Promise((resolve, reject) => {
const isDataUrl = file.match(/^data:.+?;base64,/);
if (isDataUrl) {
// NB should use sync version of `sizeOf()` for buffers
try {
const data = Buffer.from(file.slice(isDataUrl[0].length), 'base64');
return resolve(sizeForFileName('', sizeOf(data)));
} catch (err) {
return reject(err);
}
}
sizeOf(file, (err, size) => {
if (err) {
reject(err);
} else {
resolve(sizeForFileName(path.basename(file), size));
}
});
});
} | javascript | function getImageSizeFromFile(file) {
return new Promise((resolve, reject) => {
const isDataUrl = file.match(/^data:.+?;base64,/);
if (isDataUrl) {
// NB should use sync version of `sizeOf()` for buffers
try {
const data = Buffer.from(file.slice(isDataUrl[0].length), 'base64');
return resolve(sizeForFileName('', sizeOf(data)));
} catch (err) {
return reject(err);
}
}
sizeOf(file, (err, size) => {
if (err) {
reject(err);
} else {
resolve(sizeForFileName(path.basename(file), size));
}
});
});
} | [
"function",
"getImageSizeFromFile",
"(",
"file",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"const",
"isDataUrl",
"=",
"file",
".",
"match",
"(",
"/",
"^data:.+?;base64,",
"/",
")",
";",
"if",
"(",
"isDataUr... | Get image size from file on local file system
@param {String} file
@return {Promise} | [
"Get",
"image",
"size",
"from",
"file",
"on",
"local",
"file",
"system"
] | a7b4a447647e493d1edf9df3fb901740c9fbc384 | https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/image-size.js#L27-L49 |
32,989 | emmetio/atom-plugin | lib/image-size.js | getImageSizeFromURL | function getImageSizeFromURL(url) {
return new Promise((resolve, reject) => {
url = parseUrl(url);
const transport = url.protocol === 'https:' ? https : http;
transport.get(url, resp => {
const chunks = [];
let bufSize = 0;
const trySize = chunks => {
try {
const size = sizeOf(Buffer.concat(chunks, bufSize));
resp.removeListener('data', onData);
resp.destroy(); // no need to read further
resolve(sizeForFileName(path.basename(url.pathname), size));
} catch(err) {
// might not have enough data, skip error
}
};
const onData = chunk => {
bufSize += chunk.length;
chunks.push(chunk);
trySize(chunks);
};
resp
.on('data', onData)
.on('end', () => trySize(chunks))
.once('error', err => {
resp.removeListener('data', onData);
reject(err);
});
})
.once('error', reject);
});
} | javascript | function getImageSizeFromURL(url) {
return new Promise((resolve, reject) => {
url = parseUrl(url);
const transport = url.protocol === 'https:' ? https : http;
transport.get(url, resp => {
const chunks = [];
let bufSize = 0;
const trySize = chunks => {
try {
const size = sizeOf(Buffer.concat(chunks, bufSize));
resp.removeListener('data', onData);
resp.destroy(); // no need to read further
resolve(sizeForFileName(path.basename(url.pathname), size));
} catch(err) {
// might not have enough data, skip error
}
};
const onData = chunk => {
bufSize += chunk.length;
chunks.push(chunk);
trySize(chunks);
};
resp
.on('data', onData)
.on('end', () => trySize(chunks))
.once('error', err => {
resp.removeListener('data', onData);
reject(err);
});
})
.once('error', reject);
});
} | [
"function",
"getImageSizeFromURL",
"(",
"url",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"url",
"=",
"parseUrl",
"(",
"url",
")",
";",
"const",
"transport",
"=",
"url",
".",
"protocol",
"===",
"'https:'",
... | Get image size from given remove URL
@param {String} url
@return {Promise} | [
"Get",
"image",
"size",
"from",
"given",
"remove",
"URL"
] | a7b4a447647e493d1edf9df3fb901740c9fbc384 | https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/image-size.js#L56-L92 |
32,990 | emmetio/atom-plugin | lib/image-size.js | sizeForFileName | function sizeForFileName(fileName, size) {
const m = fileName.match(/@(\d+)x\./);
const scale = m ? +m[1] : 1;
return {
realWidth: size.width,
realHeight: size.height,
width: Math.floor(size.width / scale),
height: Math.floor(size.height / scale)
};
} | javascript | function sizeForFileName(fileName, size) {
const m = fileName.match(/@(\d+)x\./);
const scale = m ? +m[1] : 1;
return {
realWidth: size.width,
realHeight: size.height,
width: Math.floor(size.width / scale),
height: Math.floor(size.height / scale)
};
} | [
"function",
"sizeForFileName",
"(",
"fileName",
",",
"size",
")",
"{",
"const",
"m",
"=",
"fileName",
".",
"match",
"(",
"/",
"@(\\d+)x\\.",
"/",
")",
";",
"const",
"scale",
"=",
"m",
"?",
"+",
"m",
"[",
"1",
"]",
":",
"1",
";",
"return",
"{",
"r... | Returns size object for given file name. If file name contains `@Nx` token,
the final dimentions will be downscaled by N
@param {String} fileName
@param {Object} size
@return {Object} | [
"Returns",
"size",
"object",
"for",
"given",
"file",
"name",
".",
"If",
"file",
"name",
"contains"
] | a7b4a447647e493d1edf9df3fb901740c9fbc384 | https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/image-size.js#L101-L111 |
32,991 | emmetio/atom-plugin | lib/actions/convert-data-url.js | findTokenForPoint | function findTokenForPoint(parent, point, type) {
if (!parent) {
return null;
}
if (parent.type === type) {
return parent;
}
for (let i = 0, il = parent.size, item; i < il; i++) {
item = parent.item(i);
if (containsPoint(item, point)) {
return findTokenForPoint(item, point, type);
}
}
} | javascript | function findTokenForPoint(parent, point, type) {
if (!parent) {
return null;
}
if (parent.type === type) {
return parent;
}
for (let i = 0, il = parent.size, item; i < il; i++) {
item = parent.item(i);
if (containsPoint(item, point)) {
return findTokenForPoint(item, point, type);
}
}
} | [
"function",
"findTokenForPoint",
"(",
"parent",
",",
"point",
",",
"type",
")",
"{",
"if",
"(",
"!",
"parent",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"parent",
".",
"type",
"===",
"type",
")",
"{",
"return",
"parent",
";",
"}",
"for",
"("... | Finds first deeply nested token of given `type` that contains given `point`
@param {Token} parent Parent CSS token
@param {Point} point
@param {String} type Token type to find
@return {Token} | [
"Finds",
"first",
"deeply",
"nested",
"token",
"of",
"given",
"type",
"that",
"contains",
"given",
"point"
] | a7b4a447647e493d1edf9df3fb901740c9fbc384 | https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/convert-data-url.js#L126-L141 |
32,992 | emmetio/atom-plugin | lib/actions/convert-data-url.js | saveAsFile | function saveAsFile(editor, data, range) {
return new Promise((resolve, reject) => {
const fileName = atom.getCurrentWindow().showSaveDialog();
if (!fileName) {
return reject(new Error('User cancelled file dialog'));
}
fs.writeFile(fileName, Buffer.from(data, 'base64'), err => {
if (err) {
return reject(err);
}
const editorPath = editor.getPath();
let displayPath = editorPath
? path.relative(editorPath, fileName)
: `file://${fileName}`;
editor.transact(() => {
// Convert Windows path separators to Unix
editor.setTextInBufferRange(range, displayPath.replace(/\\+/g, '/'));
});
resolve(fileName);
});
});
} | javascript | function saveAsFile(editor, data, range) {
return new Promise((resolve, reject) => {
const fileName = atom.getCurrentWindow().showSaveDialog();
if (!fileName) {
return reject(new Error('User cancelled file dialog'));
}
fs.writeFile(fileName, Buffer.from(data, 'base64'), err => {
if (err) {
return reject(err);
}
const editorPath = editor.getPath();
let displayPath = editorPath
? path.relative(editorPath, fileName)
: `file://${fileName}`;
editor.transact(() => {
// Convert Windows path separators to Unix
editor.setTextInBufferRange(range, displayPath.replace(/\\+/g, '/'));
});
resolve(fileName);
});
});
} | [
"function",
"saveAsFile",
"(",
"editor",
",",
"data",
",",
"range",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"const",
"fileName",
"=",
"atom",
".",
"getCurrentWindow",
"(",
")",
".",
"showSaveDialog",
"(",... | Saves given base64-encoded string as file on file system
@param {TextEditor} editor
@param {String} data Base64-encoded file
@param {Range} range Editor’s replacement where saved file URL should
be written
@return {Promise} | [
"Saves",
"given",
"base64",
"-",
"encoded",
"string",
"as",
"file",
"on",
"file",
"system"
] | a7b4a447647e493d1edf9df3fb901740c9fbc384 | https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/convert-data-url.js#L151-L176 |
32,993 | emmetio/atom-plugin | lib/actions/convert-data-url.js | readFile | function readFile(fileName) {
if (/^https?:/.test(fileName)) {
return readFileFromURL(fileName);
}
return new Promise((resolve, reject) => {
fs.readFile(fileName, (err, content) => err ? reject(err) : resolve(content));
});
} | javascript | function readFile(fileName) {
if (/^https?:/.test(fileName)) {
return readFileFromURL(fileName);
}
return new Promise((resolve, reject) => {
fs.readFile(fileName, (err, content) => err ? reject(err) : resolve(content));
});
} | [
"function",
"readFile",
"(",
"fileName",
")",
"{",
"if",
"(",
"/",
"^https?:",
"/",
".",
"test",
"(",
"fileName",
")",
")",
"{",
"return",
"readFileFromURL",
"(",
"fileName",
")",
";",
"}",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject"... | Reads contents of given file path or URL as buffer
@param {String} fileName File path or URL
@return {Promise} | [
"Reads",
"contents",
"of",
"given",
"file",
"path",
"or",
"URL",
"as",
"buffer"
] | a7b4a447647e493d1edf9df3fb901740c9fbc384 | https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/convert-data-url.js#L206-L214 |
32,994 | emmetio/atom-plugin | lib/actions/insert-line-break.js | hasScope | function hasScope(descriptor, scope) {
for (let i = 0; i < descriptor.scopes.length; i++) {
if (descriptor.scopes[i].includes(scope)) {
return true;
}
}
return false;
} | javascript | function hasScope(descriptor, scope) {
for (let i = 0; i < descriptor.scopes.length; i++) {
if (descriptor.scopes[i].includes(scope)) {
return true;
}
}
return false;
} | [
"function",
"hasScope",
"(",
"descriptor",
",",
"scope",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"descriptor",
".",
"scopes",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"descriptor",
".",
"scopes",
"[",
"i",
"]",
".",
... | Check if given scope descriptor contains given scope
@param {ScopeDescriptor} descriptor
@param {String} scope
@return {Boolean} | [
"Check",
"if",
"given",
"scope",
"descriptor",
"contains",
"given",
"scope"
] | a7b4a447647e493d1edf9df3fb901740c9fbc384 | https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/insert-line-break.js#L46-L54 |
32,995 | emmetio/atom-plugin | lib/actions/insert-line-break.js | insertFormattedLineBreak | function insertFormattedLineBreak(cursor) {
const indent = cursor.editor.getTabText();
const lineIndent = getLineIndent(cursor);
cursor.selection.insertText(`\n${lineIndent}${indent}\n${lineIndent}`, { autoIndent: false });
// Put caret at the end of indented newline
cursor.moveUp();
cursor.moveToEndOfLine();
} | javascript | function insertFormattedLineBreak(cursor) {
const indent = cursor.editor.getTabText();
const lineIndent = getLineIndent(cursor);
cursor.selection.insertText(`\n${lineIndent}${indent}\n${lineIndent}`, { autoIndent: false });
// Put caret at the end of indented newline
cursor.moveUp();
cursor.moveToEndOfLine();
} | [
"function",
"insertFormattedLineBreak",
"(",
"cursor",
")",
"{",
"const",
"indent",
"=",
"cursor",
".",
"editor",
".",
"getTabText",
"(",
")",
";",
"const",
"lineIndent",
"=",
"getLineIndent",
"(",
"cursor",
")",
";",
"cursor",
".",
"selection",
".",
"insert... | Inserts formated line break for given cursor
@param {Cursor} cursor | [
"Inserts",
"formated",
"line",
"break",
"for",
"given",
"cursor"
] | a7b4a447647e493d1edf9df3fb901740c9fbc384 | https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/insert-line-break.js#L68-L77 |
32,996 | emmetio/atom-plugin | lib/actions/edit-point.js | isAtCodePoint | function isAtCodePoint(stream) {
const code = stream.peek();
// between quotes, looks like an empty attribute value
return (isQuote(code) && getPrevCode(stream) === code)
// between tags, e.g. > and <
|| (code === 60 /* < */ && getPrevCode(stream) === 62 /* > */)
// on empty line
|| (isLineBreak(code) && reEmptyLine.test(stream.buffer.lineForRow(stream.pos.row)));
} | javascript | function isAtCodePoint(stream) {
const code = stream.peek();
// between quotes, looks like an empty attribute value
return (isQuote(code) && getPrevCode(stream) === code)
// between tags, e.g. > and <
|| (code === 60 /* < */ && getPrevCode(stream) === 62 /* > */)
// on empty line
|| (isLineBreak(code) && reEmptyLine.test(stream.buffer.lineForRow(stream.pos.row)));
} | [
"function",
"isAtCodePoint",
"(",
"stream",
")",
"{",
"const",
"code",
"=",
"stream",
".",
"peek",
"(",
")",
";",
"// between quotes, looks like an empty attribute value",
"return",
"(",
"isQuote",
"(",
"code",
")",
"&&",
"getPrevCode",
"(",
"stream",
")",
"==="... | Check if stream is currently at edit code point
@param {BufferStreamReader} stream
@return {Boolean} | [
"Check",
"if",
"stream",
"is",
"currently",
"at",
"edit",
"code",
"point"
] | a7b4a447647e493d1edf9df3fb901740c9fbc384 | https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/edit-point.js#L57-L66 |
32,997 | emmetio/atom-plugin | lib/actions/edit-point.js | getPrevCode | function getPrevCode(stream) {
if (!stream.sof()) {
const code = stream.backUp(1);
stream.next();
return code;
}
} | javascript | function getPrevCode(stream) {
if (!stream.sof()) {
const code = stream.backUp(1);
stream.next();
return code;
}
} | [
"function",
"getPrevCode",
"(",
"stream",
")",
"{",
"if",
"(",
"!",
"stream",
".",
"sof",
"(",
")",
")",
"{",
"const",
"code",
"=",
"stream",
".",
"backUp",
"(",
"1",
")",
";",
"stream",
".",
"next",
"(",
")",
";",
"return",
"code",
";",
"}",
"... | Returns precediong character code for current position
@param {BufferStreamReader} stream
@return {Number} | [
"Returns",
"precediong",
"character",
"code",
"for",
"current",
"position"
] | a7b4a447647e493d1edf9df3fb901740c9fbc384 | https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/edit-point.js#L73-L79 |
32,998 | emmetio/atom-plugin | lib/actions/update-image-size.js | updateImageSizeHTML | function updateImageSizeHTML(editor, model) {
const pos = editor.getCursorBufferPosition();
const src = getImageSrcHTML( getImageHTMLNode(editor, model, pos) );
if (!src) {
return Promise.reject(new Error('No valid image source'));
}
locateFile(editor, src)
.then(getImageSize)
.then(size => {
// since this action is asynchronous, we have to ensure that editor wasn’t
// changed and user didn’t moved caret outside <img> node
const img = getImageHTMLNode(editor, model, pos);
if (getImageSrcHTML(img) === src) {
updateHTMLTag(editor, img, size.width, size.height);
}
})
.catch(err => console.warn('Error while updating image size:', err));
} | javascript | function updateImageSizeHTML(editor, model) {
const pos = editor.getCursorBufferPosition();
const src = getImageSrcHTML( getImageHTMLNode(editor, model, pos) );
if (!src) {
return Promise.reject(new Error('No valid image source'));
}
locateFile(editor, src)
.then(getImageSize)
.then(size => {
// since this action is asynchronous, we have to ensure that editor wasn’t
// changed and user didn’t moved caret outside <img> node
const img = getImageHTMLNode(editor, model, pos);
if (getImageSrcHTML(img) === src) {
updateHTMLTag(editor, img, size.width, size.height);
}
})
.catch(err => console.warn('Error while updating image size:', err));
} | [
"function",
"updateImageSizeHTML",
"(",
"editor",
",",
"model",
")",
"{",
"const",
"pos",
"=",
"editor",
".",
"getCursorBufferPosition",
"(",
")",
";",
"const",
"src",
"=",
"getImageSrcHTML",
"(",
"getImageHTMLNode",
"(",
"editor",
",",
"model",
",",
"pos",
... | Updates image size of context tag of HTML model
@param {TextEditor} editor
@param {SyntaxModel} model
@return {Promise} | [
"Updates",
"image",
"size",
"of",
"context",
"tag",
"of",
"HTML",
"model"
] | a7b4a447647e493d1edf9df3fb901740c9fbc384 | https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/update-image-size.js#L31-L50 |
32,999 | emmetio/atom-plugin | lib/actions/update-image-size.js | updateImageSizeCSS | function updateImageSizeCSS(editor, model) {
const pos = editor.getCursorBufferPosition();
const property = getImageCSSNode(editor, model, pos);
const urlToken = findUrlToken(property, pos);
const src = urlToken && getImageSrcCSS(urlToken);
if (!src) {
return Promise.reject(new Error('No valid image source'));
}
locateFile(editor, src)
.then(getImageSize)
.then(size => {
// since this action is asynchronous, we have to ensure that editor wasn’t
// changed and user didn’t moved caret outside <img> node
if (getImageCSSNode(editor, model, pos) === property) {
updateCSSNode(editor, property, size.width, size.height);
}
})
.catch(err => console.warn('Error while updating image size:', err));
} | javascript | function updateImageSizeCSS(editor, model) {
const pos = editor.getCursorBufferPosition();
const property = getImageCSSNode(editor, model, pos);
const urlToken = findUrlToken(property, pos);
const src = urlToken && getImageSrcCSS(urlToken);
if (!src) {
return Promise.reject(new Error('No valid image source'));
}
locateFile(editor, src)
.then(getImageSize)
.then(size => {
// since this action is asynchronous, we have to ensure that editor wasn’t
// changed and user didn’t moved caret outside <img> node
if (getImageCSSNode(editor, model, pos) === property) {
updateCSSNode(editor, property, size.width, size.height);
}
})
.catch(err => console.warn('Error while updating image size:', err));
} | [
"function",
"updateImageSizeCSS",
"(",
"editor",
",",
"model",
")",
"{",
"const",
"pos",
"=",
"editor",
".",
"getCursorBufferPosition",
"(",
")",
";",
"const",
"property",
"=",
"getImageCSSNode",
"(",
"editor",
",",
"model",
",",
"pos",
")",
";",
"const",
... | Updates image size of context rule of stylesheet model
@param {TextEditor} editor
@param {SyntaxModel} model
@return {Promise} | [
"Updates",
"image",
"size",
"of",
"context",
"rule",
"of",
"stylesheet",
"model"
] | a7b4a447647e493d1edf9df3fb901740c9fbc384 | https://github.com/emmetio/atom-plugin/blob/a7b4a447647e493d1edf9df3fb901740c9fbc384/lib/actions/update-image-size.js#L58-L78 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.