_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q41900 | train | function(schema, form) {
var asyncTemplates = [];
var merged = schemaForm.merge(schema, form, ignore, scope.options, undefined, asyncTemplates);
if (asyncTemplates.length > 0) {
// Pre load all async templates and put them on the form for the builder to use.
$q.all(asyncTemplates.map(function(form) {
return $http.get(form.templateUrl, {cache: $templateCache}).then(function(res) {
form.template = res.data;
});
})).then(function() {
internalRender(schema, form, merged);
});
} else {
internalRender(schema, form, merged);
}
} | javascript | {
"resource": ""
} | |
q41901 | train | function(viewValue) {
//console.log('validate called', viewValue)
//Still might be undefined
if (!form) {
return viewValue;
}
// Omit TV4 validation
if (scope.options && scope.options.tv4Validation === false) {
return viewValue;
}
var result = sfValidator.validate(form, viewValue);
//console.log('result is', result)
// Since we might have different tv4 errors we must clear all
// errors that start with tv4-
Object.keys(ngModel.$error)
.filter(function(k) { return k.indexOf('tv4-') === 0; })
.forEach(function(k) { ngModel.$setValidity(k, true); });
if (!result.valid) {
// it is invalid, return undefined (no model update)
ngModel.$setValidity('tv4-' + result.error.code, false);
error = result.error;
// In Angular 1.3+ return the viewValue, otherwise we inadvertenly
// will trigger a 'parse' error.
// we will stop the model value from updating with our own $validator
// later.
if (ngModel.$validators) {
return viewValue;
}
// Angular 1.2 on the other hand lacks $validators and don't add a 'parse' error.
return undefined;
}
return viewValue;
} | javascript | {
"resource": ""
} | |
q41902 | get_association_keys | train | function get_association_keys(collection) {
// Loop over the keys, filter irrelevant ones and fetch alias'
return Object.keys(collection._attributes || collection.attributes)
// We only care about attributes with model, collection or foreignKey properties.
.filter(key =>
collection._attributes[key].hasOwnProperty("model") ||
collection._attributes[key].hasOwnProperty("collection") ||
(
collection._attributes[key].hasOwnProperty("foreignKey") &&
collection._attributes[key].hasOwnProperty("references")
)
)
} | javascript | {
"resource": ""
} |
q41903 | get_associated_collections | train | function get_associated_collections(collection) {
const map = new Map()
get_association_keys(collection)
// Return the identity to the related resource.
.forEach(key => {
// Get the attributes
const collection_attributes = collection._attributes[key]
// Most of the time, it's a one to one
// relationship so it's not an array.
let is_array = false
// But sometimes, it's a one to many
// so array must be true.
if (collection_attributes.hasOwnProperty("collection")) {
is_array = true
}
// Set the values.
map.set(key, { is_array, collection })
})
return map
} | javascript | {
"resource": ""
} |
q41904 | streamInjectLrScript | train | function streamInjectLrScript (opts) {
opts = opts || {}
assert.equal(typeof opts, 'object')
const protocol = opts.protocol || 'http'
const host = opts.host || 'localhost'
const port = opts.port || 35729
var lrTag = '<script type="text/javascript"'
lrTag += 'src="'
lrTag += protocol
lrTag += '://'
lrTag += host
lrTag += ':'
lrTag += port
lrTag += '/livereload.js?snipver=1">'
lrTag += '</script>'
return hyperstream({ body: { _appendHtml: lrTag } })
} | javascript | {
"resource": ""
} |
q41905 | isStream | train | function isStream(io) {
return typeof io === 'object' &&
(
// Readable stream.
(typeof io.pipe === 'function' && typeof io.readable === 'boolean' &&
io.readable) ||
// Writable stream.
(typeof io.write === 'function' && typeof io.writable === 'boolean' &&
io.writable)
);
} | javascript | {
"resource": ""
} |
q41906 | reportableIntervalURL | train | function reportableIntervalURL(sourceIds) {
var url = (baseURL() +'/range/interval?nodeId=' +nodeId);
if ( Array.isArray(sourceIds) ) {
url += '&sourceIds=' + sourceIds.map(function(e) { return encodeURIComponent(e); }).join(',');
}
return url;
} | javascript | {
"resource": ""
} |
q41907 | mixin | train | function mixin(dest, src) {
if (type(src) == 'function') {
extend(dest, src.prototype)
}
else {
extend(dest, src)
}
} | javascript | {
"resource": ""
} |
q41908 | inheritFrom | train | function inheritFrom(parentConstructor, childConstructor, prototypeProps, constructorProps) {
// Create a child constructor if one wasn't given
if (childConstructor == null) {
childConstructor = function() {
parentConstructor.apply(this, arguments)
}
}
// Make sure the new prototype has the correct constructor set up
prototypeProps.constructor = childConstructor
// Base constructors should only have the properties they're defined with
if (parentConstructor !== Concur) {
// Inherit the parent's prototype
inherits(childConstructor, parentConstructor)
childConstructor.__super__ = parentConstructor.prototype
}
// Add prototype properties - this is why we took a copy of the child
// constructor reference in extend() - if a .constructor had been passed as a
// __mixins__ and overitten prototypeProps.constructor, these properties would
// be getting set on the mixed-in constructor's prototype.
extend(childConstructor.prototype, prototypeProps)
// Add constructor properties
extend(childConstructor, constructorProps)
return childConstructor
} | javascript | {
"resource": ""
} |
q41909 | saveUserProfileInCache | train | function saveUserProfileInCache(userProfile) {
var old = userProfileCache.peek(userProfile.nick);
if (old && old.updatedAt > userProfile.updatedAt) {
return;
}
userProfileCache.set(userProfile.nick, userProfile);
} | javascript | {
"resource": ""
} |
q41910 | Bot | train | function Bot(credentials, globalObject, initializationCompleteCallback) {
LOG.info("Attempting to log in with email {}", credentials.username);
new DubAPI(credentials, (function(err, _bot) {
if (err) {
throw new Error("Error occurred when logging in: " + err);
}
this.bot = _bot;
LOG.info("Logged in successfully");
// Set up an error handler so errors don't cause the bot to crash
this.bot.on('error', function(err) {
LOG.error("Unhandled error occurred; swallowing it so bot keeps running. Error: {}", err);
});
// Reconnect the bot automatically if it disconnects
this.bot.on('disconnected', (function(roomName) {
LOG.warn("Disconnected from room {}. Reconnecting..", roomName);
this.connect(roomName);
}).bind(this));
// Set up custom event handling to insulate us from changes in the dubtrack API
this.eventHandlers = {};
for (var eventKey in Types.Event) {
var eventName = Types.Event[eventKey];
this.eventHandlers[eventName] = [];
}
if (globalObject.config.DubBotBase.logAllEvents) {
LOG.info("Logging of all events is enabled. Setting up logging event handlers.");
for (var eventKey in Types.Event) {
var eventName = Types.Event[eventKey];
LOG.info("Hooking into eventKey {}, eventName {}", eventKey, eventName);
this.bot.on(eventName, (function(name) {
return function(event) {
LOG.info("event '{}' has JSON payload: {}", name, event);
};
})(eventName));
}
}
for (var eventKey in Types.Event) {
var eventName = Types.Event[eventKey];
var translatorFunction = _eventTranslatorMap[eventName];
this.bot.on(eventName, _createEventDispatcher(eventName, translatorFunction, globalObject).bind(this));
}
if (initializationCompleteCallback) {
initializationCompleteCallback(this);
}
}).bind(this));
} | javascript | {
"resource": ""
} |
q41911 | _createEventDispatcher | train | function _createEventDispatcher(internalEventName, translator, globalObject) {
return function(event) {
var handlers = this.eventHandlers[internalEventName];
if (!translator) {
LOG.error("Could not find a translator for internalEventName {}", internalEventName);
return;
}
var internalObject = translator(event);
if (!internalObject) {
return;
}
internalObject.eventName = internalEventName;
for (var i = 0; i < handlers.length; i++) {
handlers[i].callback.call(handlers[i].context, internalObject, globalObject);
}
};
} | javascript | {
"resource": ""
} |
q41912 | printResults | train | function printResults(results){
var output = "";
var dependenciesTimes = [];
var devDependenciesTimes = [];
dependenciesTimes = Object.keys(results.moduleTimes.dependencies).map(function(depen){
var val = results.moduleTimes.dependencies[depen];
return [
chalk.gray(depen),
" : ",
chalk.white(val === -1 ? "Cannot be required" : val)
];
});
devDependenciesTimes = Object.keys(results.moduleTimes.devDependencies).map(function(depen){
var val = results.moduleTimes.devDependencies[depen];
return [
chalk.gray(depen),
" : ",
chalk.white(val === -1 ? "Cannot be required" : val)
];
});
if(dependenciesTimes.length > 0){
output += chalk.white("Dependencies: \n");
output += table(dependenciesTimes, {align: ["l", "l"]});
}
if(devDependenciesTimes.length > 0){
output += chalk.white("\n\nDevDependencies: \n");
output += table(devDependenciesTimes, {align : ["l", "l"]});
}
output += chalk.white("\n\nModule load time: " + (results.loadTime === -1 ? "Cannot be required" : results.loadTime));
console.log(output);
} | javascript | {
"resource": ""
} |
q41913 | execute | train | function execute(args){
var options = optionator.parse(args);
if(options.help){
console.log(optionator.generateHelp());
}
else if(options.version){
console.log("v" + require("../package.json").version);
}
else{
printResults(loadPerf(options));
}
} | javascript | {
"resource": ""
} |
q41914 | grepLines | train | function grepLines(src, ext, destFile){
src = grunt.util.normalizelf(src);
var lines = src.split(grunt.util.linefeed),
dest = [],
//pattern for all comments containing denotation
denotationPattern = updatePattern({
pattern: options.pattern,
ext: ext,
isDenotationPattern: true}),
//pattern for one-line grep usage
pattern = updatePattern({
pattern: options.pattern,
ext: ext}),
//patterns for multi-line grep usage
startPattern = updatePattern({
pattern:options.pattern,
augmentPattern: options.startPattern,
ext: ext}),
endPattern = updatePattern({
pattern: options.pattern,
augmentPattern: options.endPattern,
ext: ext});
if (pattern !== false){
var startedRemoving;
//loop over each line looking for either pattern or denotation comments
lines.forEach(function(line) {
if (!startedRemoving){
//looking for one-line or start of multi-line pattern
if (line.search(startPattern) === -1 ){
//looking for one-line or start of one-line pattern
if (line.search(pattern) === -1 ){
//looking for denotation comments
if (options.removeDenotationComments && line.search(denotationPattern) !== -1){
var lineDenotationLess = line.replace(new RegExp(denotationPattern), '');
dest.push(lineDenotationLess);
} else {
//none of patterns found
dest.push(line);
}
}
} else{
//multi-line found
startedRemoving = true;
}
} else {
//looking for end of multi-line pattern
if (line.search(endPattern) !== -1 ){
startedRemoving = false;
}
}
});
var destText = dest.join(grunt.util.linefeed);
if (grunt.file.exists(destFile)){
if (!options.fileOverride){
grunt.fail.warn('File "' + destFile + '" already exists, though is specified as a dest file. ' +
'Turn on option "fileOverride" so that old file is removed first.');
} else {
grunt.file.delete(destFile);
}
}
grunt.file.write(destFile, destText);
grunt.log.writeln('File "' + destFile + '" created.');
} else {
grunt.log.warn('Pattern for \'' + task.target + '\' should be a string.');
}
} | javascript | {
"resource": ""
} |
q41915 | onResponse | train | function onResponse (res) {
endTime = getTimeMs(endTime)
res = Object.assign(res, { opDuration: endTime })
if (res.error) {
appendRes = res
} else {
log.info(
{
res: res,
duration: endTime
},
'end of the request'
)
}
} | javascript | {
"resource": ""
} |
q41916 | define | train | function define(style, string) {
var split = string.split(' ');
for (var i = 0; i < split.length; i++) {
words[split[i]] = style;
}
} | javascript | {
"resource": ""
} |
q41917 | Honey | train | function Honey(options) {
options = options || {};
assert.isString(options.apiKey, 'Honeybadger transport needs an "apiKey" config option');
this.name = 'honeybadger';
this.apiKey = options.apiKey;
if(!options.logger) {
options.logger = console;
}
this.remote = new Badger(options);
winston.Transport.call(this, options);
} | javascript | {
"resource": ""
} |
q41918 | parseInput | train | function parseInput(input) {
var match = re.exec(input);
if (match !== null) {
var _match = _slicedToArray(match, 6),
pre_keyword = _match[1],
operator_keyword = _match[2],
value = _match[3],
unit = _match[4],
post_keyword = _match[5];
if (pre_keyword && post_keyword || pre_keyword && operator_keyword || post_keyword && operator_keyword) {
return null;
}
return {
value: sanitizeValue({
value: value,
operator_keyword: operator_keyword,
post_keyword: post_keyword
}),
unit: unit
};
}
return null;
} | javascript | {
"resource": ""
} |
q41919 | sanitizeValue | train | function sanitizeValue(_ref) {
var value = _ref.value,
operator_keyword = _ref.operator_keyword,
post_keyword = _ref.post_keyword;
return parseInt(value, 10) * getMultiplier({
operator_keyword: operator_keyword,
post_keyword: post_keyword
});
} | javascript | {
"resource": ""
} |
q41920 | getMultiplier | train | function getMultiplier(_ref2) {
var operator_keyword = _ref2.operator_keyword,
post_keyword = _ref2.post_keyword;
return operator_keyword === '-' || post_keyword === 'ago' ? -1 : 1;
} | javascript | {
"resource": ""
} |
q41921 | _default | train | function _default(input) {
var parsed_input = parseInput(input);
if (parsed_input !== null) {
var value = parsed_input.value,
unit = parsed_input.unit;
return relative_time_units[unit] * value;
}
return null;
} | javascript | {
"resource": ""
} |
q41922 | train | function (text, plugin) {
debug(`Job "${this.id}" comments:`, plugin || '<no plugin>', text);
this.status('command.comment', {
comment: text,
plugin: plugin,
time: new Date()
});
} | javascript | {
"resource": ""
} | |
q41923 | train | function (pluginName, env, path) {
var self = this;
var context = {
status: this.status.bind(this),
out: this.out.bind(this),
comment: function (text) {
self.comment(text, pluginName);
},
cmd: function (cmd, next) {
if (typeof(cmd) === 'string' || cmd.command) {
cmd = {cmd: cmd};
}
cmd.env = _.extend({}, env, {
PATH: getPath(path),
HOME: process.env.HOME || (process.env.HOMEDRIVE + process.env.HOMEPATH),
LANG: process.env.LANG,
SSH_AUTH_SOCK: process.env.SSH_AUTH_SOCK,
PAAS_NAME: 'strider'
}, cmd.env || {});
return self.cmd(cmd, pluginName, next);
},
// update pluginData
data: function (data, method, path) {
self.status('plugin-data', {
plugin: pluginName,
data: data,
method: method,
path: path
});
},
dataDir: this.config.dataDir,
baseDir: this.config.baseDir,
cacheDir: this.config.cacheDir,
cachier: this.config.cachier(pluginName),
io: this.io,
plugin: pluginName,
phase: this.phase,
job: this.job,
branch: this.job.ref.branch,
project: this.project,
runnerId: (
this.config.branchConfig
&& this.config.branchConfig.runner
&& this.config.branchConfig.runner.id || 'unkown'
)
};
return context;
} | javascript | {
"resource": ""
} | |
q41924 | RunGruntTask | train | function RunGruntTask(taskname,absolutePath) {
var exec = require('child_process').exec;
var gruntarg = ' --gruntfile ';
var space = ' ';
if (os === 'Windows_NT') {
gruntPath = 'node_modules\\grunt-cli\\bin\\grunt' || absolutePath;
var ShellTask = gruntPath + space + gruntarg + gruntfile + space + taskname;
var GruntTask = new shell(ShellTask);
GruntTask.on('output', function(data) {
console.log(data);
});
GruntTask.on('end', function(code) {
console.log("Execution done");
});
}
if (os === 'Darwin' || os === 'Linux') {
gruntPath = 'node_modules/grunt-cli/bin/grunt';
var child = exec(gruntPath + gruntarg + gruntfile + space + taskname, function(error, stdout, stderr) {
if (error !== null) {
console.log('exec error: ' + error);
var stdout = error;
return stdout;
} else {
console.log('stdout: ' + stdout);
return stdout;
}
});
}
} | javascript | {
"resource": ""
} |
q41925 | fetch | train | function fetch(url, id) {
var req = http.request(url, function (res) {
res.pipe(terminus.concat(function (contents) {
tx.end(id, {type: "fetch", url: url, code: res.statusCode})
}))
})
req.end()
} | javascript | {
"resource": ""
} |
q41926 | Ask | train | function Ask(options) {
if (!(this instanceof Ask)) {
return new Ask(options);
}
this.options = options || {};
this.questions = utils.questions(this.options.questions);
var store = this.options.store;
var name = store && store.name;
if (!name) name = 'ask-once.' + utils.project(process.cwd());
this.answers = utils.store(name, store);
this.previous = utils.store(name + '.previous', this.answers.options);
Object.defineProperty(this, 'data', {
enumerable: true,
get: function () {
return this.answers.data;
}
});
} | javascript | {
"resource": ""
} |
q41927 | basename | train | function basename(file){
var extname = path.extname(file);
return path.basename(file, extname);
} | javascript | {
"resource": ""
} |
q41928 | hexToRgb | train | function hexToRgb(hex) {
var match = hex.toString(16).match(/[a-f0-9]{6}/i);
if (!match) {
return {r: 0, g: 0, b: 0};
}
var integer = parseInt(match[0], 16);
var r = (integer >> 16) & 0xFF;
var g = (integer >> 8) & 0xFF;
var b = integer & 0xFF;
return {
r: r,
g: g,
b: b
};
} | javascript | {
"resource": ""
} |
q41929 | train | function (dir_path) {
return fs.statAsync(dir_path)
.call('isDirectory')
.then(function (isDirectory) {
if (isDirectory) {
return fs.readdirAsync(dir_path)
.map(function (file_name) {
var file_path = dir_path + '/' + file_name;
return fs.statAsync(file_path)
.then(function (stat) {
return {
isDirectory: stat.isDirectory(),
file_path: file_path
}
})
})
.reduce(function (files, file_item) {
if (file_item.isDirectory) {
return getFilesByDir(file_item.file_path)
.then(function (subDirFiles) {
return files.concat(subDirFiles)
})
}
files.push(file_item.file_path);
return files
}, [])
}
throw new Error('Please input a valid directory!');
})
} | javascript | {
"resource": ""
} | |
q41930 | hasMany | train | function hasMany(config) {
var association;
association = {
type : 'HAS_MANY',
name : config.name || config,
cardinality : 'many',
targetModel : config.targetModel || config,
localProperty : config.localProperty || 'id',
targetProperty : config.targetProperty || (config + 'Id')
};
this.prototype[association.name] = function(callback){
var model = this;
var targetModel = window;
association.targetModel.split('.').forEach(function (property) {
targetModel = targetModel[property];
});
targetModel.all(function (data) {
var result = data.filter(function (instance) {
return instance[association.targetProperty] === model[association.localProperty];
});
if (callback) {
callback(result);
}
});
};
return this;
} | javascript | {
"resource": ""
} |
q41931 | promptingHelper | train | function promptingHelper( generator, generator_prompts ) {
var prompts = filterPrompts( generator.options.PromptAnswers, generator_prompts );
return generator.prompt( prompts )
.then(
function ( answers ) {
addPromptAnswers( generator.options.PromptAnswers, answers );
}
);
} | javascript | {
"resource": ""
} |
q41932 | xfer | train | function xfer (res, files, cb) {
var file = files.shift();
if (!file) {
return cb(null);
}
fs.createReadStream(file
).on("data", function (chunk) {
res.write(chunk);
}).on("error", cb
).on("close", function xferClose () {
xfer(res, files, cb);
});
} | javascript | {
"resource": ""
} |
q41933 | train | function( editor, parentElement, definition, level ) {
definition.forceIFrame = 1;
// In case of editor with floating toolbar append panels that should float
// to the main UI element.
if ( definition.toolbarRelated && editor.elementMode == CKEDITOR.ELEMENT_MODE_INLINE )
parentElement = CKEDITOR.document.getById( 'cke_' + editor.name );
var doc = parentElement.getDocument(),
panel = getPanel( editor, doc, parentElement, definition, level || 0 ),
element = panel.element,
iframe = element.getFirst(),
that = this;
// Disable native browser menu. (#4825)
element.disableContextMenu();
this.element = element;
this._ = {
editor: editor,
// The panel that will be floating.
panel: panel,
parentElement: parentElement,
definition: definition,
document: doc,
iframe: iframe,
children: [],
dir: editor.lang.dir
};
editor.on( 'mode', hide );
editor.on( 'resize', hide );
// Window resize doesn't cause hide on blur. (#9800)
// [iOS] Poping up keyboard triggers window resize
// which leads to undesired panel hides.
if ( !CKEDITOR.env.iOS )
doc.getWindow().on( 'resize', hide );
// We need a wrapper because events implementation doesn't allow to attach
// one listener more than once for the same event on the same object.
// Remember that floatPanel#hide is shared between all instances.
function hide() {
that.hide();
}
} | javascript | {
"resource": ""
} | |
q41934 | train | function() {
// Webkit requires to blur any previous focused page element, in
// order to properly fire the "focus" event.
if ( CKEDITOR.env.webkit ) {
var active = CKEDITOR.document.getActive();
active && !active.equals( this._.iframe ) && active.$.blur();
}
// Restore last focused element or simply focus panel window.
var focus = this._.lastFocused || this._.iframe.getFrameDocument().getWindow();
focus.focus();
} | javascript | {
"resource": ""
} | |
q41935 | train | function( panel, blockName, offsetParent, corner, offsetX, offsetY ) {
// Skip reshowing of child which is already visible.
if ( this._.activeChild == panel && panel._.panel._.offsetParentId == offsetParent.getId() )
return;
this.hideChild();
panel.onHide = CKEDITOR.tools.bind( function() {
// Use a timeout, so we give time for this menu to get
// potentially focused.
CKEDITOR.tools.setTimeout( function() {
if ( !this._.focused )
this.hide();
}, 0, this );
}, this );
this._.activeChild = panel;
this._.focused = false;
panel.showBlock( blockName, offsetParent, corner, offsetX, offsetY );
this.blur();
/* #3767 IE: Second level menu may not have borders */
if ( CKEDITOR.env.ie7Compat || CKEDITOR.env.ie6Compat ) {
setTimeout( function() {
panel.element.getChild( 0 ).$.style.cssText += '';
}, 100 );
}
} | javascript | {
"resource": ""
} | |
q41936 | grabUrls | train | function grabUrls (opts) {
opts.shortcode.forEach(function (shortcode) {
instagrab.url(shortcode, opts.size, function (err, url) {
console.log(err || url)
})
})
} | javascript | {
"resource": ""
} |
q41937 | grabImages | train | function grabImages (opts) {
if (!opts.quiet) console.log(multiline(function () {/*
_ _| | |
| __ \ __| __| _` | _` | __| _` | __ \
| | | \__ \ | ( | ( | | ( | | |
___| _| _| ____/ \__| \__,_| \__, | _| \__,_| _.__/
|___/
*/}))
opts.shortcode.forEach(function (shortcode) {
// set up the sink
var filename = instagrab.filename(shortcode, opts.size)
var filepath = path.join(process.cwd(), filename)
var toFile = fs.createWriteStream(filepath)
toFile.on('error', onSaveError(shortcode))
toFile.on('finish', function onSaved () {
if (this.quiet) return;
console.log('grabbed: ', filename)
})
// grab the bits
return instagrab(shortcode, opts.size)
.on('error', onGrabError(shortcode))
.pipe(toFile)
})
} | javascript | {
"resource": ""
} |
q41938 | createCopy | train | function createCopy(inPath, outPath) {
if (!inPath) {
throw new Error('Input path(s) argument is required');
}
if (!outPath) {
throw new Error('Output path argument is required');
}
return function copyFiles() {
return gulp.src(inPath).pipe(gulp.dest(outPath));
};
} | javascript | {
"resource": ""
} |
q41939 | logConfigFile | train | function logConfigFile(configFile, logger) {
let message;
if (process.env.WORKER_ID !== undefined) {
message = `Worker ${process.env.WORKER_ID} uses configuration file: ${configFile}`;
} else {
message = `Supervisor uses configuration file: ${configFile}`;
}
if (logger && logger.verbose) {
logger.verbose(message);
} else {
// eslint-disable-next-line no-console
console.log(message);
}
} | javascript | {
"resource": ""
} |
q41940 | train | function() {
element.find('a, button').mousemove(function(e) {
if (buttonPickerEnabled) {
if (e.target !== buttonToPickElement) {
buttonToPickCounter = 0;
buttonToPickElement = e.target;
}
buttonToPickCounter += 1;
if (buttonToPickCounter > 50) {
element.find('a, button').css('border', '');
$(e.target).css('border', 'solid 2px green');
var createSelector = function(element) {
if (element.attr('id')) {
return '#' + element.attr('id');
} else {
var classes = element.attr('class').split(/\s/);
return classes.map(function(x) {
return '.' + x;
}).join('');
}
};
if (buttonToPick === 'undo') {
editor.find('.kelmu-editor-undo-button').val(createSelector($(e.target)));
} else if (buttonToPick === 'redo') {
editor.find('.kelmu-editor-redo-button').val(createSelector($(e.target)));
} else if (buttonToPick === 'step') {
editor.find('.kelmu-editor-step-button').val(createSelector($(e.target)));
} else if (buttonToPick === 'begin') {
editor.find('.kelmu-editor-begin-button').val(createSelector($(e.target)));
}
buttonPickerEnabled = false;
buttonToPickCounter = 0;
setTimeout(function() {
element.find('a, button').css('border', '');
}, 5000);
}
}
});
buttonPickerCreated = true;
} | javascript | {
"resource": ""
} | |
q41941 | train | function() {
var elem = $(this);
var data = window.kelmu.data[id];
data.selectedElementNumber = parseInt(elem.attr('data-annotation'), 10);
var elemData = data.definitions['step' + data.stepNumber][data.subStepNumber][data.selectedElementNumber];
if (elemData.rotate) {
elem.css('transform', 'none');
elem.css('moz-transform', 'none');
elem.css('webkit-transform', 'none');
elem.css('ms-transform', 'none');
}
} | javascript | {
"resource": ""
} | |
q41942 | train | function() {
var elem = $(this);
var data = window.kelmu.data[id];
data.selectedElementNumber = parseInt(elem.attr('data-annotation'), 10);
var elemData = data.definitions['step' + data.stepNumber][data.subStepNumber][data.selectedElementNumber];
elemData.top = parseFloat(elem.css('top'));
elemData.left = parseFloat(elem.css('left'));
if (elem.hasClass('kelmu-annotation')) {
elemData.height = elem.height();
elemData.width = elem.width();
}
} | javascript | {
"resource": ""
} | |
q41943 | train | function() {
container.find('.kelmu-annotation, .kelmu-button').mousedown(resetRotation);
container.find('.kelmu-annotation, .kelmu-button').mouseup(restoreRotation);
container.find('.kelmu-annotation, .kelmu-button').draggable({
start: function() {
var elem = $(this);
var data = window.kelmu.data[id];
data.selectedElementNumber = parseInt(elem.attr('data-annotation'), 10);
resetRotation.call(this);
},
stop: function() {
restoreRotation.call(this);
updatePosition.call(this);
notifyModifications();
updateView(false, true);
}
});
container.find('.kelmu-annotation-content, .kelmu-button').css('cursor', 'move');
} | javascript | {
"resource": ""
} | |
q41944 | train | function() {
container.find('.kelmu-annotation').resizable({
start: function() {
var elem = $(this);
var data = window.kelmu.data[id];
data.selectedElementNumber = parseInt(elem.attr('data-annotation'), 10);
if (elem.css('background-color') === 'transparent' || elem.css('background-color') === 'rgba(0, 0, 0, 0)') {
elem.css('background-color', 'rgba(0, 0, 0, 0.1)');
}
},
stop: function() {
restoreRotation.call(this);
updatePosition.call(this);
notifyModifications();
updateView(false, true);
}
});
} | javascript | {
"resource": ""
} | |
q41945 | train | function(event) {
if (event.ctrlKey) {
return;
}
event.preventDefault();
var elem = $(this);
var data = window.kelmu.data[id];
data.selectedElementNumber = parseInt(elem.attr('data-annotation'), 10);
updateView(false, true);
} | javascript | {
"resource": ""
} | |
q41946 | train | function(text, container, name, value, type, noBr) {
var idNumber = idCounter;
if (!noBr) {
$('<br>').appendTo(container);
}
$('<label></label>').attr('for', animationId + '-' + name + '-' + idNumber).text(text).appendTo(container);
if (type === 'text') {
$('<input type="text"></input>').addClass(name).attr('id', animationId + '-' + name + '-' + idNumber).val(value).appendTo(container);
} else if (type === 'checkbox') {
$('<input></input>').addClass(name).attr('type', 'checkbox').attr('id', animationId + '-' + name + '-' + idNumber).prop('checked', value).appendTo(container);
} else if (type === 'textarea') {
$('<textarea></textarea>').addClass(name).attr('id', animationId + '-' + name + '-' + idNumber).val(value).appendTo(container);
}
idCounter += 1;
} | javascript | {
"resource": ""
} | |
q41947 | train | function() {
// Remove the element
return $('<button></button>').text('Remove').addClass('btn').click(function(e) {
e.preventDefault();
var data = window.kelmu.data[id];
data.definitions['step' + data.stepNumber][data.subStepNumber].splice(window.kelmu.data[id].selectedElementNumber, 1);
window.kelmu.data[id].selectedElementNumber = -1;
window.kelmu.data[id].actions.update();
updateView(true, true);
notifyModifications();
});
} | javascript | {
"resource": ""
} | |
q41948 | train | function() {
var data = window.kelmu.data[id];
var elemData = data.definitions['step' + data.stepNumber][data.subStepNumber][data.selectedElementNumber];
editor.find('.kelmu-editor-pane').remove();
var actionEditor = $('<div></div>').addClass('kelmu-action-editor').addClass('kelmu-editor-pane');
actionEditor.appendTo(editor);
actionEditor.append($('<h4>Action</h4>').css('margin', '15px 0px'));
idCounter += 1;
// Set the current values
addComponent('Action:', actionEditor, 'kelmu-action-type', elemData.action, 'text', true);
addComponent('Parameter:', actionEditor, 'kelmu-action-parameter', elemData.parameter, 'text');
addComponent('State:', actionEditor, 'kelmu-action-when', elemData.when, 'text');
// Move cursor to end
actionEditor.find('.kelmu-action-type').focus();
var val = actionEditor.find('.kelmu-action-type').val();
actionEditor.find('.kelmu-action-type').val('').val(val);
var buttonContainer = $('<div></div>').appendTo(actionEditor);
// Save the modified properties
var saveButton = function() {
elemData.action = actionEditor.find('.kelmu-action-type').val() || window.kelmu.defaults.action.action;
elemData.parameter = actionEditor.find('.kelmu-action-parameter').val() || window.kelmu.defaults.action.parameter;
elemData.when = actionEditor.find('.kelmu-action-when').val() || window.kelmu.defaults.action.when;
window.kelmu.data[id].actions.update();
updateView(true, true);
notifyModifications();
};
actionEditor.find('input').keyup(saveButton);
createRemoveButton().appendTo(buttonContainer);
// Set current properties as default settings
$('<button></button>').text('Make default').addClass('btn').appendTo(buttonContainer).click(function(e) {
e.preventDefault();
window.kelmu.defaults.action.action = actionEditor.find('.kelmu-action-type').val() || actionDefaults.action;
window.kelmu.defaults.action.parameter = actionEditor.find('.kelmu-action-parameter').val() || actionDefaults.parameter;
window.kelmu.defaults.action.when = actionEditor.find('.kelmu-action-when').val() || actionDefaults.when;
});
} | javascript | {
"resource": ""
} | |
q41949 | train | function() {
var data = window.kelmu.data[id];
var elemData = data.definitions['step' + data.stepNumber][data.subStepNumber][data.selectedElementNumber];
editor.find('.kelmu-editor-pane').remove();
var arrowEditor = $('<div></div>').addClass('kelmu-arrow-editorr').addClass('kelmu-editor-pane');
arrowEditor.appendTo(editor);
arrowEditor.append($('<h4>Arrow</h4>').css('margin', '15px 0px'));
idCounter += 1;
// Set the current values
addComponent('Size:', arrowEditor, 'kelmu-arrow-size', elemData.size, 'text', true);
addComponent('Width:', arrowEditor, 'kelmu-arrow-width', elemData.width, 'text');
addComponent('Color:', arrowEditor, 'kelmu-arrow-color', elemData.arrow, 'text');
addComponent('With sound:', arrowEditor, 'kelmu-arrow-sound-option', elemData.soundOption, 'text');
// Save the modified properties
var saveArrow = function() {
elemData.size = arrowEditor.find('.kelmu-arrow-size').val() || window.kelmu.defaults.arrow.size;
elemData.width = arrowEditor.find('.kelmu-arrow-width').val() || window.kelmu.defaults.arrow.width;
elemData.arrow = arrowEditor.find('.kelmu-arrow-color').val() || window.kelmu.defaults.arrow.arrow;
elemData.soundOption = arrowEditor.find('.kelmu-arrow-sound-option').val() || window.kelmu.defaults.arrow.soundOption;
window.kelmu.data[id].actions.update();
updateView(true, true);
notifyModifications();
};
arrowEditor.find('input').keyup(saveArrow);
var buttonContainer = $('<div></div>').appendTo(arrowEditor);
createRemoveButton().appendTo(buttonContainer);
// Save the modified properties
$('<button></button>').text('Make default').addClass('btn').appendTo(buttonContainer).click(function(e) {
e.preventDefault();
window.kelmu.defaults.arrow.width = arrowEditor.find('.kelmu-arrow-width').val() || arrowDefaults.width;
window.kelmu.defaults.arrow.arrow = arrowEditor.find('.kelmu-arrow-color').val() || arrowDefaults.arrow;
window.kelmu.defaults.arrow.size = arrowEditor.find('.kelmu-arrow-size').val() || arrowDefaults.size;
window.kelmu.defaults.arrow.soundOption = arrowEditor.find('.kelmu-arrow-sound-option').val() || arrowDefaults.soundOption;
});
} | javascript | {
"resource": ""
} | |
q41950 | train | function() {
var data = window.kelmu.data[id];
var elemData = data.definitions['step' + data.stepNumber][data.subStepNumber][data.selectedElementNumber];
editor.find('.kelmu-editor-pane').remove();
var lineEditor = $('<div></div>').addClass('kelmu-line-editor').addClass('kelmu-editor-pane');
lineEditor.appendTo(editor);
lineEditor.append($('<h4>Line</h4>').css('margin', '15px 0px'));
idCounter += 1;
// Set the current values
addComponent('Width:', lineEditor, 'kelmu-line-width', elemData.width, 'text', true);
addComponent('Color:', lineEditor, 'kelmu-line-color', elemData.line, 'text');
addComponent('With sound:', lineEditor, 'kelmu-line-sound-option', elemData.soundOption, 'text');
// Save the modified properties
var saveLine = function() {
elemData.width = lineEditor.find('.kelmu-line-width').val() || window.kelmu.defaults.line.width;
elemData.line = lineEditor.find('.kelmu-line-color').val() || window.kelmu.defaults.line.line;
elemData.soundOption = lineEditor.find('.kelmu-line-sound-option').val() || window.kelmu.defaults.line.soundOption;
window.kelmu.data[id].actions.update();
updateView(true, true);
notifyModifications();
};
lineEditor.find('input').keyup(saveLine);
var buttonContainer = $('<div></div>').appendTo(lineEditor);
createRemoveButton().appendTo(buttonContainer);
// Save the modified properties
$('<button></button>').text('Make default').addClass('btn').appendTo(buttonContainer).click(function(e) {
e.preventDefault();
window.kelmu.defaults.line.width = lineEditor.find('.kelmu-line-width').val() || lineDefaults.width;
window.kelmu.defaults.line.line = lineEditor.find('.kelmu-line-color').val() || lineDefaults.line;
window.kelmu.defaults.line.soundOption = lineEditor.find('.kelmu-line-sound-option').val() || lineDefaults.soundOption;
});
} | javascript | {
"resource": ""
} | |
q41951 | train | function() {
var data = window.kelmu.data[id];
var elemData = data.definitions['step' + data.stepNumber][data.subStepNumber][data.selectedElementNumber];
editor.find('.kelmu-editor-pane').remove();
var soundEditor = $('<div></div>').addClass('kelmu-sound-editor').addClass('kelmu-editor-pane');
soundEditor.appendTo(editor);
soundEditor.append($('<h4>Sound</h4>').css('margin', '15px 0px'));
idCounter += 1;
// Set the current values
addComponent('URL:', soundEditor, 'kelmu-sound-url', elemData.sound, 'text', true);
// Move cursor to end
soundEditor.find('.kelmu-sound-url').focus();
var val = soundEditor.find('.kelmu-sound-url').val();
soundEditor.find('.kelmu-sound-url').val('').val(val);
var buttonContainer = $('<div></div>').appendTo(soundEditor);
// Save the modified properties
var saveButton = function() {
elemData.sound = soundEditor.find('.kelmu-sound-url').val();
window.kelmu.data[id].actions.update();
updateView(true, true);
notifyModifications();
};
soundEditor.find('input').keyup(saveButton);
createRemoveButton().click(function(e) {
e.preventDefault();
var soundControl = container.find('.kelmu-sound-control');
soundControl.hide();
// If there are sounds for this animation, show the mute control
Object.keys(window.kelmu.data[id].definitions || {}).forEach(function(substeps) {
window.kelmu.data[id].definitions[substeps].forEach(function(substep) {
substep.forEach(function(step) {
if (step.sound !== undefined) {
soundControl.show();
}
});
});
});
}).appendTo(buttonContainer);
// Play the sound
$('<button></button>').text('Play').addClass('btn').appendTo(buttonContainer).click(function(e) {
e.preventDefault();
var sound = $('<audio></audio>').attr('src', soundEditor.find('.kelmu-sound-url').val());
container.append(sound);
sound[0].play();
});
} | javascript | {
"resource": ""
} | |
q41952 | train | function($, $ln, contents) {
var ln = $ln[0]
, attrKeys = Object.keys(ln.attribs)
, $s = $('<style type="text/css"></style>')
, attrs = []
, ix;
for(ix = attrKeys.length; ix--;) {
$s.attr(attrKeys[ix], ln.attribs[attrKeys[ix]]);
}
// Save the origin href
// ...
$s.attr('data-bepacked-href', $s.attr('href'));
$s.attr('href', null);
$s.attr('rel', null);
$s.text(contents.toString().trim());
$ln.replaceWith($s);
} | javascript | {
"resource": ""
} | |
q41953 | train | function() {
// Let's fade out the splash screen div...
$('.splash').fadeOut('slow', function() {
// ...stop the pulsing effect...
$('.splash .circle').stop().css({
opacity : 1
});
// and fade in the content div.
$('.content').fadeIn('slow', function() {
if (people.length == 0)
$('#title').fadeIn('slow');
else
greet(people, 0);
});
});
} | javascript | {
"resource": ""
} | |
q41954 | getFormDataForPost | train | function getFormDataForPost(fields, files) {
function encodeFieldPart(boundary, name, value) {
var return_part = "--" + boundary + "\r\n";
return_part += "Content-Disposition: form-data; name=\"" + name + "\"\r\n\r\n";
return_part += value + "\r\n";
return return_part;
}
function encodeFilePart(boundary, type, name, filename) {
var return_part = "--" + boundary + "\r\n";
return_part += "Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + filename + "\"\r\n";
return_part += "Content-Type: " + type + "\r\n\r\n";
return return_part;
}
var boundary = Math.random();
var post_data = [];
if (fields) {
for (var key in fields) {
var value = fields[key];
post_data.push(new Buffer(encodeFieldPart(boundary, key, value), 'ascii'));
}
}
if (files) {
for (var key in files) {
var value = files[key];
post_data.push(new Buffer(encodeFilePart(boundary, value.type, value.keyname, value.valuename), 'ascii'));
post_data.push(new Buffer(value.data, 'utf8'))
}
}
post_data.push(new Buffer("\r\n--" + boundary + "--"), 'ascii');
var length = 0;
for (var i = 0; i < post_data.length; i++) {
length += post_data[i].length;
}
var params = {
postdata: post_data,
headers: {
'Content-Type': 'multipart/form-data; boundary=' + boundary,
'Content-Length': length
}
};
return params;
} | javascript | {
"resource": ""
} |
q41955 | postData | train | function postData(fields, files, options, headers, callback) {
var headerparams = getFormDataForPost(fields, files);
var totalheaders = headerparams.headers;
for (var key in headers) totalheaders[key] = headers[key];
var post_options = {
host: options.host,
port: options.port,
path: options.path,
method: options.method || 'POST',
headers: totalheaders
};
var request = Http.request(post_options, function(response) {
response.body = '';
response.setEncoding(options.encoding);
response.on('data', function(chunk) {
console.log(chunk);
response.body += chunk;
});
response.on('end', function() {
callback(null, response)
});
});
for (var i = 0; i < headerparams.postdata.length; i++) {
request.write(headerparams.postdata[i]);
}
request.end();
} | javascript | {
"resource": ""
} |
q41956 | postImage | train | function postImage(options, filename, headers, cb) {
Step(
function readImage() {
fs.readFile(filename, this);
},
function(err, filecontents) {
if (err) {
console.log('Unable to read file', __dirname);
return;
}
postData(null, [{
type: 'image/jpeg',
keyname: 'image',
valuename: 'image.jpg',
data: filecontents
}], options, headers, this);
},
function(err, response, body) {
cb && cb(err, response);
console.log("response code " + response.statusCode, ", body is : ", body);
}
);
} | javascript | {
"resource": ""
} |
q41957 | Nonce | train | function Nonce(cache, ttl) {
this.cache = cache;
this.ttl = ttl;
if (this.ttl && this.ttl > TTLMAX) {
this.ttl = TTLMAX;
}
} | javascript | {
"resource": ""
} |
q41958 | createCoincap | train | function createCoincap () {
const socket = io(baseUrl, { autoConnect: false })
const api = {}
// Add JSON API supported endpoints
;[
{
method: 'coins',
url: () => '/coins'
},
{
method: 'map',
url: () => '/map'
},
{
method: 'front',
url: () => '/front'
},
{
method: 'global',
url: () => '/global'
},
{
method: 'coin',
url: coin => `/page/${coin}`
},
{
method: 'coinHistory',
url: (coin, days) => `/history/${days ? `${days}day/` : ''}${coin}`
}
].forEach(function ({ method, url }) {
api[method] = (...args) => fetch(url(...args))
})
// Add Socket.IO methods
;[
'open',
'close',
'on',
'off'
].forEach(function (method) {
api[method] = socket[method].bind(socket)
})
return api
} | javascript | {
"resource": ""
} |
q41959 | logInfo | train | function logInfo () {
console.log(`Running on node ${process.version} with ${os.cpus()[0].model} x ${os.cpus().length}`);
console.log('');
console.log('Testing:');
var columns = columnsCreate(['name', 'version', 'homepage']);
var infoStatic = require('serve-static/package.json');
infoStatic.version = 'v' + infoStatic.version;
columnsUpdate(columns, infoStatic);
var infoStatique = require('statique/package.json');
infoStatique.version = 'v' + infoStatique.version;
columnsUpdate(columns, infoStatique);
var infoFiles = require('../package.json');
infoFiles.version = 'v' + infoFiles.version;
columnsUpdate(columns, infoFiles);
console.log('- ' + columnsText(columns, infoStatic));
console.log('- ' + columnsText(columns, infoStatique));
console.log('- ' + columnsText(columns, infoFiles));
console.log('');
function columnsCreate (names) {
return names.map(name => {
return {size: 0, source: name};
});
}
function columnsUpdate (columns, info) {
var size;
var col;
for (var i = 0; i < columns.length; i++) {
col = columns[i];
size = (info[col.source] && info[col.source].length) || 0;
if (info[col.source] && (size = info[col.source].length) && size > col.size) {
col.size = size;
}
}
}
function columnsText (columns, info) {
var result = '';
for (var i = 0; i < columns.length; i++) {
result += columnText(columns[i], info);
result += ' ';
}
return result + ' ';
}
function columnText (column, info) {
var value = info[column.source] || '';
var padSize = column.size - value.length;
var pad = '';
if (padSize) {
pad += (new Array(padSize + 1)).join(' ');
}
return value + pad;
}
} | javascript | {
"resource": ""
} |
q41960 | fakeTask | train | function fakeTask () {
return callback => server.get(filename, (err, res) => callback(err, res));
} | javascript | {
"resource": ""
} |
q41961 | send | train | function send(statusCode, body) {
if (body) {
body = JSON.stringify(body);
}
return {
statusCode,
body
};
} | javascript | {
"resource": ""
} |
q41962 | train | function(src,dest, isfile){
//console.log('test');
if (isfile){
grunt.file.copy(src,dest+'/'+src,{});
console.log('File has been created as '+dest+'/'+src);
return;
}
grunt.file.recurse(src, function(abspath, rootdir, subdir, filename){
var _ref3=(typeof subdir=='undefined'?'':(subdir+'/'));
grunt.file.copy(abspath,dest+'/'+src+'/'+_ref3+filename, {});
console.log('File has been created as '+dest+'/'+src+'/'+filename);
});
} | javascript | {
"resource": ""
} | |
q41963 | tail | train | function tail (argv, callback) {
if (!argv[2]) {
console.error('url is required')
console.error('Usage : tail <url>')
process.exit(-1)
}
var uri = argv[2]
var wss = 'wss://' + uri.split('/')[2] + '/'
var s = new ws(wss, {
origin: 'http://websocket.org'
})
s.on('open', function open () {
s.send('sub ' + uri)
})
s.on('close', function close () {
console.log('disconnected')
})
s.on('message', function message (data, flags) {
var a = data.split(' ')
if (a.length && a[0] === 'pub') {
util.get(a[1], function (err, res) {
if (err) {
console.error('Error : ' + err)
} else {
console.log(res)
}
})
}
})
} | javascript | {
"resource": ""
} |
q41964 | radicalInverse_VdC | train | function radicalInverse_VdC(i) {
bits[0] = i;
bits[0] = ((bits[0] << 16) | (bits[0] >> 16))>>>0;
bits[0] = ((bits[0] & 0x55555555) << 1) | ((bits[0] & 0xAAAAAAAA) >>> 1) >>>0;
bits[0] = ((bits[0] & 0x33333333) << 2) | ((bits[0] & 0xCCCCCCCC) >>> 2) >>>0;
bits[0] = ((bits[0] & 0x0F0F0F0F) << 4) | ((bits[0] & 0xF0F0F0F0) >>> 4) >>>0;
bits[0] = ((bits[0] & 0x00FF00FF) << 8) | ((bits[0] & 0xFF00FF00) >>> 8) >>>0;
return bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
} | javascript | {
"resource": ""
} |
q41965 | genEnvOptions | train | function genEnvOptions(commitMsg) {
return {
pluginName : globalOpts.pluginName,
pluginDesc : globalOpts.pluginDesc,
pkgPath : 'package.json',
pkgPathBower : 'bower.json',
pkgPropSync : [ 'name', 'version', 'repository' ],
gitCliSubstitute : '',
buildDir : process.env.TRAVIS_BUILD_DIR || process.cwd(),
branch : process.env.TRAVIS_BRANCH,
commitHash : process.env.TRAVIS_COMMIT,
commitMessage : commitMsg || process.env.TRAVIS_COMMIT_MESSAGE,
repoSlug : process.env.TRAVIS_REPO_SLUG,
releaseVersionDefaultLabel : 'release',
releaseVersionDefaultType : 'v',
releaseVersionRegExp : globalOpts.regexRelease,
releaseVersionSemverIncRegExp : globalOpts.regexReleaseSemverInc,
bumpVersionDefaultLabel : 'bump',
bumpVersionDefaultType : 'v',
bumpVersionRegExp : globalOpts.regexBump,
bumpVersionSemverIncRegExp : globalOpts.regexBumpSemverInc,
prevVersionMsgIgnoreRegExp : /No names found/i,
gitToken : process.env.GH_TOKEN,
npmToken : process.env.NPM_TOKEN
};
} | javascript | {
"resource": ""
} |
q41966 | genTaskOptions | train | function genTaskOptions(env) {
var mp = env.pluginName + ': ';
return {
name : '<%= commit.versionTag %>',
pkgCurrVerBumpMsg : mp
+ 'Updating <%= env.pkgPath %> version to match release version <%= commit.version %> <%= commit.skipTaskGen(options.releaseSkipTasks) %>',
pkgNextVerBumpMsg : mp
+ 'Bumping <%= env.pkgPath %> version to <%= commit.next.version %> <%= commit.skipTaskGen(options.releaseSkipTasks) %>',
distBranchPubMsg : mp + 'Publishing <%= commit.version %> <%= commit.skipTaskGen(options.releaseSkipTasks) %>',
pkgJsonReplacer : null,
pkgJsonSpace : 2,
gitHostname : github.hostname,
repoName : 'origin',
repoUser : env.pluginName,
repoEmail : env.pluginName + '@' + (process.env.TRAVIS_BUILD_NUMBER ? 'travis-ci.org' : 'example.org'),
chgLog : 'HISTORY.md',
authors : 'AUTHORS.md',
chgLogLineFormat : ' * %s',
chgLogRequired : true,
chgLogSkipRegExps : [ mp ],
authorsRequired : false,
authorsSkipLineRegExp : null,
distBranch : 'gh-pages',
distDir : 'dist',
distBranchCreateRegExp : /Couldn't find remote ref/i,
distExcludeDirRegExp : /.?node_modules.?/gmi,
distExcludeFileRegExp : /.?\.zip|tar.?/gmi,
distAssetCompressRatio : 9,
distAssetDir : '..',
distAssetUpdateFunction : null,
distAssetUpdateFiles : [],
distBranchUpdateFunction : null,
distBranchUpdateFiles : [],
rollbackStrategy : 'queue',
rollbackAsyncTimeout : 60000,
asyncTimeout : 60000,
releaseSkipTasks : [ 'ci' ],
npmTag : '',
npmRegistryURL : 'https://registry.npmjs.org'
};
} | javascript | {
"resource": ""
} |
q41967 | getLineReplRegExp | train | function getLineReplRegExp(rxa, tasks) {
var r = '', sf = null;
function rxItem(o, i, a) {
var s = util.isRegExp(o) ? o.source : escapeRegExp(o);
if (s) {
r += (sf ? sf(true, s) : '(?:' + s + ')') + (i < (a.length - 1) ? '|' : '');
}
}
if (Array.isArray(rxa) && rxa.length) {
rxa.forEach(rxItem);
// join tasks with or clause
r += '|';
}
var tsks = Array.isArray(tasks) ? tasks : [];
if (tsks.indexOf(chgLog) < 0) {
tsks.push(chgLog);
}
sf = committer.skipTaskGen;
tsks.forEach(rxItem);
return new RegExp('^.*(' + r + ').*$\n?\r?', 'gmi');
} | javascript | {
"resource": ""
} |
q41968 | applyExtensions | train | function applyExtensions(hoodie) {
for (var i = 0; i < extensions.length; i++) {
extensions[i](hoodie);
}
} | javascript | {
"resource": ""
} |
q41969 | WriteArray | train | function WriteArray (options, callback) {
var self = this
if (!(this instanceof WriteArray)) {
return new WriteArray(options, callback)
}
if (typeof options === 'function') {
callback = options
options = {}
}
options = Object.assign({}, options)
Writable.call(self, options)
self.array = []
self.callback = callback
self.on('pipe', function (src) {
src.on('error', function (err) {
self.callback(err)
})
})
self.on('finish', function () {
self.callback(null, self.array)
})
return self
} | javascript | {
"resource": ""
} |
q41970 | getGameAfterMoves | train | function getGameAfterMoves(game, moves) {
return moves.reduce(function (lastGame, move) {
return getGameAfterMove(lastGame, move);
}, game);
} | javascript | {
"resource": ""
} |
q41971 | sortFontSizes | train | function sortFontSizes(fontSizes) {
var r = {};
var temp = [];
var size = 0;
var biggest = 0;
for (var prop in fontSizes) {
if (fontSizes.hasOwnProperty(prop)) {
size++;
var val = prop.replace(/[^0-9.\/]/g, '').replace(/\/[0-9]/g, '');
if (prop.indexOf('%') > -1) {
val = 16 / 100 * val;
}
if (prop.indexOf('em') > -1
|| prop.indexOf('rem') > -1
|| prop.indexOf('vw') > -1
|| prop.indexOf('vh') > -1) {
val = 16 * val;
}
if (val === '') {
val = prop;
}
biggest = val > biggest ? val : biggest;
if (/[0-9.]/g.test(val)) {
temp.push({
viewSizePx: val,
viewSizeStr: '',
cssSize: prop,
amount: fontSizes[prop]
});
} else {
temp.push({
viewSizePx: 0,
viewSizeStr: val,
cssSize: prop,
amount: fontSizes[prop]
});
}
}
}
r = temp.sort(function (a, b) {
return b.viewSizePx - a.viewSizePx;
});
return r;
} | javascript | {
"resource": ""
} |
q41972 | getValueCount | train | function getValueCount(values, property) {
var arr = {};
property = property ? property : '';
if (!values) {
grunt.log.writeln(app.chalkWarn('no ' + property + ' defined in your css'));
return arr;
}
values.forEach(function (v) {
v = v.replace(/['"]/g, '');
if (arr.hasOwnProperty(v)) {
arr[v] = arr[v] + 1;
} else {
arr[v] = 1;
}
});
return arr;
} | javascript | {
"resource": ""
} |
q41973 | deindentBlocks | train | function deindentBlocks(input) {
var indent = detectIndent(input).indent
return input.replace(regex.blocks, function (match, start, body, end) {
return start + deindent(body, indent) + end
})
} | javascript | {
"resource": ""
} |
q41974 | train | function() {
var self = this;
var relations = utils.argToArr.call(arguments);
var func = function(s, e) {
if(!s)
return s;
var alls = [];
var doGet = function(entry) {
if (!entry.schema || !entry.schema.links)
return;
var r = {
value: entry.value,
schema: entry.schema
};
querier.query(entry.schema.links, "./*?rel=in=(" + relations.join(",") + ")")
.forEach(function(relation) {
//console.log("getRelations : got : ", relation)
var path = utils.interpret(relation.href, entry.value);
var parsed = utils.parseRequest(path);
var wrap = {
rel: relation,
href: parsed
};
r[relation] = wrap;
alls.push(protoc.get(parsed, {
wrap: wrap
}));
});
}
if(s._deep_array_)
s.forEach(doGet);
else if(s._deep_query_node_)
doGet(s);
if (alls.length)
return prom.all(alls);
return null;
};
func._isDone_ = true;
return self._enqueue(func);
} | javascript | {
"resource": ""
} | |
q41975 | train | function(map, delimitter) {
if (!delimitter)
delimitter = ".";
var self = this;
var relations = [];
for (var i in map)
relations.push(i);
//console.log("mapRelations : relations : ", relations);
var func = function(s, e) {
if(!s || (!s._deep_query_node_ && !s._deep_array_))
return s;
var doMap = function(entry) {
if (!entry.schema || !entry.schema.links)
return;
var alls = [];
querier.query(entry.schema.links, "./*?rel=in=(" + relations.join(",") + ")")
.forEach(function(relation) {
//console.log("do map relations on : ", relation);
var path = utils.interpret(relation.href, entry.value);
alls.push(protoc.get(path, {
defaultProtocole: "json",
wrap: {
path: map[relation.rel]
}
}));
});
var d = prom.all(alls)
.done(function(results) {
//console.log("mapRelations : results : ");
//console.log(JSON.stringify(results));
results.forEach(function(r) {
//console.log("do : ", r, " - on : ", entry.value)
utils.toPath(entry.value, r.path, r.result, delimitter);
});
return results;
});
promises.push(d);
};
var promises = [];
if(s._deep_array_)
s.forEach(doMap);
else
doMap(s);
if (!promises.length)
return s;
return prom.all(promises)
.done(function() {
return s;
});
};
func._isDone_ = true;
return self._enqueue(func);
} | javascript | {
"resource": ""
} | |
q41976 | create_header_col | train | function create_header_col(m) {
var $e = $$('hcol nowrap');
$e.css({width: p});
if (m.options) {
$e.css(m.options);
}
$e.text(m.name);
var hilight = function () {
if (!order)
return;
if (order == m.name)
{
$e.addClass('order asc');
$lh = $e;
}
else if (order.substring(1) == m.name)
{
$e.addClass('order desc');
$lh = $e;
}
}
hilight();
$e.click(function () {
if (order == m.name) {
order = '-' + m.name;
}
else {
order = m.name;
}
zcookie.set('order-'+type, order);
if ($lh)
$lh.removeClass('order asc desc');
hilight();
$lh = $e;
request_data();
});
return $e;
} | javascript | {
"resource": ""
} |
q41977 | make_page | train | function make_page(i, total) {
var $p = $$('page', {el: 'span'});
if (i == page) {
$p.addClass('selected');
$lp = $p;
}
var top = Math.min(i*pagesize+pagesize, total);
$p.text((i*pagesize+1)+'-'+top);
$p.text(i+1);
$p.click(function () {
page = i;
zcookie.set('page-'+type, page);
if ($lp)
$lp.removeClass('selected');
$lp = $p;
$lp.addClass('selected');
request_data();
});
return $p;
} | javascript | {
"resource": ""
} |
q41978 | train | function (object) {
object.id = object.id || this.generateId();
this.data.push(object);
this.mapValues[object.id] = {};
this.eachMap(function (map, mapName) {
this.addObjectToMap(mapName, object);
});
return this;
} | javascript | {
"resource": ""
} | |
q41979 | train | function (object) {
var index = this.data.indexOf(object);
if (index !== -1) {
this.data.splice(index, 1);
}
this.eachMap(function (map, mapName) {
this.removeObjectFromMap(mapName, object);
});
delete this.mapValues[object.id];
return this;
} | javascript | {
"resource": ""
} | |
q41980 | train | function (id, length) {
length = length || 8;
id = id || words.generate(length);
while (this.mapValues[id] !== undefined) {
id = words.generate(length);
length += 1;
}
return id.toString();
} | javascript | {
"resource": ""
} | |
q41981 | train | function (mapName, index) {
if (this.maps[mapName][index] === undefined) {
return [];
}
return this.maps[mapName][index].slice(); //slice() makes a copy of the array
} | javascript | {
"resource": ""
} | |
q41982 | train | function (callback) {
var mapName;
for (mapName in this.maps) {
if (this.maps.hasOwnProperty(mapName)) {
callback.call(this, this.maps[mapName], mapName);
}
}
} | javascript | {
"resource": ""
} | |
q41983 | train | function (callback) {
var i;
for (i = 0; i < this.data.length; i += 1) {
callback.call(this, this.data[i], i);
}
return this;
} | javascript | {
"resource": ""
} | |
q41984 | train | function (mapName, object) {
var mapFunction = this.mapFunctions[mapName],
index,
value,
emit = function (idx, val) {
index = idx;
value = val;
};
mapFunction.call(object, object, emit);
if (this.maps[mapName][index] === undefined) {
this.maps[mapName][index] = [];
}
this.maps[mapName][index].push(value);
this.mapValues[object.id][mapName] = index;
return this;
} | javascript | {
"resource": ""
} | |
q41985 | train | function (mapName, object) {
var mapValue = this.mapValues[object.id][mapName],
index = this.maps[mapName][mapValue].indexOf(object);
if (index !== -1) {
this.maps[mapName][mapValue].splice(index, 1);
}
return this;
} | javascript | {
"resource": ""
} | |
q41986 | AbstractAdapter | train | function AbstractAdapter(valueOrBuffer, pos) {
this.pos = pos != null ? pos : 0;
this.data = null;
if (Buffer.isBuffer(valueOrBuffer)) {
this.value = this.getValue(valueOrBuffer);
} else {
this.loadData(valueOrBuffer);
}
} | javascript | {
"resource": ""
} |
q41987 | train | function(authStore, session) {
var found = false;
for (var i = 0; i < authStore.length; i++) {
if (authStore[i].equal(session)) {
found = true;
break;
}
}
if (!found) authStore.push(session);
} | javascript | {
"resource": ""
} | |
q41988 | maxOrMin | train | function maxOrMin( args, method ) {
var m, n,
i = 0;
if ( isArray( args[0] ) ) args = args[0];
m = new BigNumber( args[0] );
for ( ; ++i < args.length; ) {
n = new BigNumber( args[i] );
// If any number is NaN, return NaN.
if ( !n.s ) {
m = n;
break;
} else if ( method.call( m, n ) ) {
m = n;
}
}
return m;
} | javascript | {
"resource": ""
} |
q41989 | raise | train | function raise( caller, msg, val ) {
var error = new Error( [
'new BigNumber', // 0
'cmp', // 1
'config', // 2
'div', // 3
'divToInt', // 4
'eq', // 5
'gt', // 6
'gte', // 7
'lt', // 8
'lte', // 9
'minus', // 10
'mod', // 11
'plus', // 12
'precision', // 13
'random', // 14
'round', // 15
'shift', // 16
'times', // 17
'toDigits', // 18
'toExponential', // 19
'toFixed', // 20
'toFormat', // 21
'toFraction', // 22
'pow', // 23
'toPrecision', // 24
'toString', // 25
'BigNumber' // 26
][caller] + '() ' + msg + ': ' + val );
error.name = 'BigNumber Error';
id = 0;
throw error;
} | javascript | {
"resource": ""
} |
q41990 | coeffToString | train | function coeffToString(a) {
var s, z,
i = 1,
j = a.length,
r = a[0] + '';
for ( ; i < j; ) {
s = a[i++] + '';
z = LOG_BASE - s.length;
for ( ; z--; s = '0' + s );
r += s;
}
// Determine trailing zeros.
for ( j = r.length; r.charCodeAt(--j) === 48; );
return r.slice( 0, j + 1 || 1 );
} | javascript | {
"resource": ""
} |
q41991 | train | function() {
var secret;
if (!this.getSecret()) {
throw new CError('missing secret').log();
}
try {
secret = this.encoder.encryptRsa(this.getSecret());
} catch (e) {
throw new CError({
body: {
code: 'ImATeapot',
message: 'unable to encrypt secret',
cause: e
}
}).log('body');
}
if (this.getMode() !== mode1 && this.getMode() !== mode2) {
throw new CError('unexpected mode').log();
}
if (!this.getSid()) {
throw new CError('missing sid').log();
}
return {
mode: this.getMode(),
secret: secret,
sid: this.getSid()
};
} | javascript | {
"resource": ""
} | |
q41992 | train | function(data) {
if (!data) {
data = this.getContent();
}
return this.encoder.encryptAes(JSON.stringify(data), this.getSecret());
} | javascript | {
"resource": ""
} | |
q41993 | train | function (options) {
this.options = $.extend(this.defaults, options);
this.$el = $.fn.mediumInsert.insert.$el;
this.setEmbedButtonEvents();
this.preparePreviousEmbeds();
} | javascript | {
"resource": ""
} | |
q41994 | Component | train | function Component(bowerObj, files) {
this.bowerObj = bowerObj;
this.files = files;
this.name = bowerObj['name'];
this.version = bowerObj['version'];
} | javascript | {
"resource": ""
} |
q41995 | MetricsService | train | function MetricsService(storageAccount, storageAccessKey, host, authenticationProvider) {
if (!host) {
// Dev Stg does not support metrics
host = azure.ServiceClient.CLOUD_TABLE_HOST;
}
MetricsService.super_.call(this, host, storageAccount, storageAccessKey, authenticationProvider);
if (!this.authenticationProvider) {
this.authenticationProvider = new azure.SharedKeyTable(this.storageAccount, this.storageAccessKey, this.usePathStyleUri);
}
} | javascript | {
"resource": ""
} |
q41996 | executeBatch | train | function executeBatch(bulkOperation, batch, options, callback) {
function resultHandler(err, result) {
// Error is a driver related error not a bulk op error, terminate
if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) {
return handleCallback(callback, err);
}
// If we have and error
if (err) err.ok = 0;
if (err instanceof MongoWriteConcernError) {
return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, false, err, callback);
}
handleCallback(
callback,
null,
mergeBatchResults(false, batch, bulkOperation.s.bulkResult, err, result)
);
}
bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback);
} | javascript | {
"resource": ""
} |
q41997 | executeBatches | train | function executeBatches(bulkOperation, options, callback) {
let numberOfCommandsToExecute = bulkOperation.s.batches.length;
// Execute over all the batches
for (let i = 0; i < bulkOperation.s.batches.length; i++) {
executeBatch(bulkOperation, bulkOperation.s.batches[i], options, function(err) {
// Count down the number of commands left to execute
numberOfCommandsToExecute = numberOfCommandsToExecute - 1;
// Execute
if (numberOfCommandsToExecute === 0) {
// Driver level error
if (err) return handleCallback(callback, err);
const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult);
if (bulkOperation.handleWriteError(callback, writeResult)) return;
return handleCallback(callback, null, writeResult);
}
});
}
} | javascript | {
"resource": ""
} |
q41998 | triggerEvent | train | function triggerEvent(name, element) {
var eventType;
switch (name) {
case "click":
case "mousedown":
case "mouseup":
eventType = "MouseEvents";
break;
case "focus":
case "change":
case "blur":
case "select":
eventType = "HTMLEvents";
break;
default:
throw new Error('Unsupported `"' + name + '"`event');
break;
}
var event = document.createEvent(eventType);
event.initEvent(name, name !== "change" , true);
element.dispatchEvent(event, true);
} | javascript | {
"resource": ""
} |
q41999 | isValid | train | function isValid(ch){
var code = ch.charCodeAt(0);
return is_letter(code)
|| is_digit(code)
|| (ch === '.')
|| (ch === '_')
|| is_unicode_connector_punctuation(ch)
|| is_unicode_format(ch)
|| is_unicode_combining_mark(ch)
|| is_unicode_digit(ch);
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.