_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q41000 | cdProjectRoot | train | function cdProjectRoot(dir) {
var projectRoot = this.isCordova(dir);
if (!projectRoot) {
throw new CordovaError('Current working directory is not a judpack project.');
}
if (!origCwd) {
origCwd = process.env.PWD || process.cwd();
}
process.env.PWD = projectRoot;
process.chdir(projectRoot);
return projectRoot;
} | javascript | {
"resource": ""
} |
q41001 | deleteSvnFolders | train | function deleteSvnFolders(dir) {
var contents = fs.readdirSync(dir);
contents.forEach(function(entry) {
var fullpath = path.join(dir, entry);
if (fs.statSync(fullpath).isDirectory()) {
if (entry == '.svn') {
shell.rm('-rf', fullpath);
} else module.exports.deleteSvnFolders(fullpath);
}
});
} | javascript | {
"resource": ""
} |
q41002 | findPlugins | train | function findPlugins(pluginPath) {
var plugins = [],
stats;
if (exports.existsSync(pluginPath)) {
plugins = fs.readdirSync(pluginPath).filter(function (fileName) {
stats = fs.statSync(path.join(pluginPath, fileName));
return fileName != '.svn' && fileName != 'CVS' && stats.isDirectory();
});
}
return plugins;
} | javascript | {
"resource": ""
} |
q41003 | getAvailableNpmVersions | train | function getAvailableNpmVersions(module_name) {
var npm = require('npm');
return Q.nfcall(npm.load).then(function () {
return Q.ninvoke(npm.commands, 'view', [module_name, 'versions'], /* silent = */ true).then(function (result) {
// result is an object in the form:
// {'<version>': {versions: ['1.2.3', '1.2.4', ...]}}
// (where <version> is the latest version)
return result[Object.keys(result)[0]].versions;
});
});
} | javascript | {
"resource": ""
} |
q41004 | execute | train | function execute(req, res) {
// TODO: ensure a conflict is triggered on all watched keys
this.store.flushall();
res.send(null, Constants.OK);
} | javascript | {
"resource": ""
} |
q41005 | bot | train | function bot(job, done) {
var jobs = job.data.jobs
console.log(job.data.jobs)
if (!jobs) {
done()
return
}
for (var i = 0; i < jobs.length; i++) {
var j = jobs[i]
debug('Running : ' + j)
}
done()
} | javascript | {
"resource": ""
} |
q41006 | train | function($li, model) {
$li.attr('todo-cid', model.cid);
$li.toggleClass('todo-done', model.done);
$li.text(model.title);
} | javascript | {
"resource": ""
} | |
q41007 | train | function (e) {
if (e && e.preventDefault) e.preventDefault();
var $el = $(e.target);
var cid = $el.attr('todo-cid');
if (cid) {
this.options.toggleItem(cid);
}
return false;
} | javascript | {
"resource": ""
} | |
q41008 | parseTextBody | train | function parseTextBody(req, res, next){
if (req.body === undefined) {
req.body = '';
req.on('data', function(chunk){ req.body += chunk });
req.on('end', next);
} else {
next();
}
} | javascript | {
"resource": ""
} |
q41009 | reload | train | function reload() {
var params = {}
params[model.primary] = me[model.primary]
var act = new NobleMachine(model.find(params));
act.next(function(newInst) {
if (newInst) {
for (var col in model.columns) {
me[col] = newInst[col];
}
act.toNext(me);
} else {
for (var key in model.columns) {
me[key] = undefined
}
act.toNext(null);
}
});
return act;
} | javascript | {
"resource": ""
} |
q41010 | destroy | train | function destroy() {
var act = new NobleMachine(function() {
if (me.onDestroy) {
var preact = me.onDestroy();
if (preact && preact.start instanceof Function) {
act.toNext(preact)
return;
}
}
});
act.next(function() {
var sql = "DELETE FROM " + model.table
+ " WHERE `" + model.primary + "` = " + me[model.primary];
act.toNext(db_query(sql));
});
act.next(function() {
logger.log("Successfully deleted `" + model.ident + "` record `" + me[model.primary] + "`");
for (var param in me) {
delete me[param];
}
});
act.error(function(err) {
logger.error("Error deleting `" + model.ident + "` record: " + JSON.stringify(err));
act.emitError(err);
});
return act;
} | javascript | {
"resource": ""
} |
q41011 | setValue | train | function setValue(key, val) {
//util.log(key + ": " + JSON.stringify(val));
if (val === null) {
me.values[key] = null;
} else if (val === undefined) {
me.values[key] = undefined;
} else {
type = model.columns[key]['DATA_TYPE'];
switch (type) {
case 'datetime':
case 'timestamp':
me.values[key] = new Date(val);
break;
case 'text':
case 'varchar':
me.values[key] = val.toString();
break;
case 'int':
case 'tinyint':
if (model.columns[key]['COLUMN_TYPE'] == 'tinyint(1)') {
me.values[key] = !!val // Boolean
} else {
me.values[key] = parseInt(val);
}
break;
default:
me.values[key] = val;
}
}
} | javascript | {
"resource": ""
} |
q41012 | InteractionManager | train | function InteractionManager(renderer, options)
{
options = options || {};
/**
* The renderer this interaction manager works for.
*
* @member {SystemRenderer}
*/
this.renderer = renderer;
/**
* Should default browser actions automatically be prevented.
*
* @member {boolean}
* @default true
*/
this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true;
/**
* As this frequency increases the interaction events will be checked more often.
*
* @member {number}
* @default 10
*/
this.interactionFrequency = options.interactionFrequency || 10;
/**
* The mouse data
*
* @member {InteractionData}
*/
this.mouse = new InteractionData();
/**
* An event data object to handle all the event tracking/dispatching
*
* @member {EventData}
*/
this.eventData = {
stopped: false,
target: null,
type: null,
data: this.mouse,
stopPropagation:function(){
this.stopped = true;
}
};
/**
* Tiny little interactiveData pool !
*
* @member {Array}
*/
this.interactiveDataPool = [];
/**
* The DOM element to bind to.
*
* @member {HTMLElement}
* @private
*/
this.interactionDOMElement = null;
/**
* Have events been attached to the dom element?
*
* @member {boolean}
* @private
*/
this.eventsAdded = false;
//this will make it so that you don't have to call bind all the time
/**
* @member {Function}
*/
this.onMouseUp = this.onMouseUp.bind(this);
this.processMouseUp = this.processMouseUp.bind( this );
/**
* @member {Function}
*/
this.onMouseDown = this.onMouseDown.bind(this);
this.processMouseDown = this.processMouseDown.bind( this );
/**
* @member {Function}
*/
this.onMouseMove = this.onMouseMove.bind( this );
this.processMouseMove = this.processMouseMove.bind( this );
/**
* @member {Function}
*/
this.onMouseOut = this.onMouseOut.bind(this);
this.processMouseOverOut = this.processMouseOverOut.bind( this );
/**
* @member {Function}
*/
this.onTouchStart = this.onTouchStart.bind(this);
this.processTouchStart = this.processTouchStart.bind(this);
/**
* @member {Function}
*/
this.onTouchEnd = this.onTouchEnd.bind(this);
this.processTouchEnd = this.processTouchEnd.bind(this);
/**
* @member {Function}
*/
this.onTouchMove = this.onTouchMove.bind(this);
this.processTouchMove = this.processTouchMove.bind(this);
/**
* @member {number}
*/
this.last = 0;
/**
* The css style of the cursor that is being used
* @member {string}
*/
this.currentCursorStyle = 'inherit';
/**
* Internal cached var
* @member {Point}
* @private
*/
this._tempPoint = new core.Point();
/**
* The current resolution
* @member {number}
*/
this.resolution = 1;
this.setTargetElement(this.renderer.view, this.renderer.resolution);
} | javascript | {
"resource": ""
} |
q41013 | lower | train | function lower (value) {
if (value === null || value === undefined) {
return value
}
return String.prototype.toLowerCase.call(value)
} | javascript | {
"resource": ""
} |
q41014 | Reporter | train | function Reporter (opts) {
this.events = opts.events;
this.config = opts.config;
this.temporaryAssertions = [];
this.temp = {};
var defaultReportFolder = 'report/dalek';
this.dest = this.config.get('html-reporter') && this.config.get('html-reporter').dest ? this.config.get('html-reporter').dest : defaultReportFolder;
this.loadTemplates();
this.initOutputHandlers();
this.startListening();
} | javascript | {
"resource": ""
} |
q41015 | train | function () {
// render stylesheets
var precss = fs.readFileSync(__dirname + '/themes/default/styl/default.styl', 'utf8');
stylus.render(precss, { filename: 'default.css' }, function(err, css){
if (err) {
throw err;
}
this.styles = css;
}.bind(this));
// collect client js (to be inined later)
this.js = fs.readFileSync(__dirname + '/themes/default/js/default.js', 'utf8');
// register handlebars helpers
Handlebars.registerHelper('roundNumber', function (number) {
return Math.round(number * Math.pow(10, 2)) / Math.pow(10, 2);
});
// collect & compile templates
this.templates = {};
this.templates.test = Handlebars.compile(fs.readFileSync(__dirname + '/themes/default/hbs/test.hbs', 'utf8'));
this.templates.wrapper = Handlebars.compile(fs.readFileSync(__dirname + '/themes/default/hbs/wrapper.hbs', 'utf8'));
this.templates.testresult = Handlebars.compile(fs.readFileSync(__dirname + '/themes/default/hbs/tests.hbs', 'utf8'));
this.templates.banner = Handlebars.compile(fs.readFileSync(__dirname + '/themes/default/hbs/banner.hbs', 'utf8'));
this.templates.detail = Handlebars.compile(fs.readFileSync(__dirname + '/themes/default/hbs/detail.hbs', 'utf8'));
return this;
} | javascript | {
"resource": ""
} | |
q41016 | train | function (data) {
this.detailContents.testResult = data;
this.detailContents.styles = this.styles;
this.detailContents.js = this.js;
fs.writeFileSync(this.dest + '/details/' + data.id + '.html', this.templates.detail(this.detailContents), 'utf8');
return this;
} | javascript | {
"resource": ""
} | |
q41017 | train | function (data) {
var body = '';
var contents = '';
var tests = '';
var banner = '';
// add test results
var keys = Object.keys(this.output.test);
keys.forEach(function (key) {
tests += this.output.test[key];
}.bind(this));
// compile the test result template
body = this.templates.testresult({result: data, tests: tests});
// compile the banner
banner = this.templates.banner({status: data.status});
// compile the contents within the wrapper template
contents = this.templates.wrapper({styles: this.styles, js: this.js, banner: banner, body: body});
// save the main test output file
this.events.emit('report:written', {type: 'html', dest: this.dest});
this._recursiveMakeDirSync(this.dest + '/details');
fs.writeFileSync(this.dest + '/index.html', contents, 'utf8');
return this;
} | javascript | {
"resource": ""
} | |
q41018 | train | function (data) {
data.assertionInfo = this.temporaryAssertions;
data.browser = this.temp.browser;
this.output.test[data.id] = this.templates.test(data);
this.temporaryAssertions = [];
return this;
} | javascript | {
"resource": ""
} | |
q41019 | train | function() {
var src = config.paths.src;
var out = config.paths.out;
src.base = src.base || 'src/';
src.styles = src.styles || 'styles/';
src.scripts = src.scripts || 'scripts/';
src.esnextExtension = src.esnextExtension || '.es6';
src.views = src.templates || '../views/';
src.partials = src.partials !== null ? src.partials : 'partials/';
out.base = out.base || 'public/';
var processed = {
src: {
styles: src.base + src.styles + '**/*' + plugins.styles.ext,
scripts: src.base + src.scripts,
es6: src.base + src.scripts + '**/*' + src.esnextExtension,
esnextExt: src.esnextExtension,
js: src.base + src.scripts + '**/*.js',
views: src.base + src.views + '**/*',
partials: src.base + src.views + src.partials + '**/*' + plugins.tpls.ext,
tmp: src.base + 'temp/'
},
out: {
base: out.base,
styles: out.base + (out.styles || 'css/'),
js: out.base + (out.scripts || 'js/')
}
};
return processed;
} | javascript | {
"resource": ""
} | |
q41020 | train | function(_gulp, _config) {
if (!_gulp) {
throw 'Error: A Gulp instance should be passed to the gulpConfig method.';
}
gulp = _gulp;
config = _config || { paths: { src: {}, out: {} } };
plugins = elaboratePlugins();
paths = elaboratePaths();
lrport = _config.liveReloadPort || lrport;
server = _config.server || (console.error(
'An Express server should be passed in the configuration.')),
serverport = _config.port || serverport;
cleanTmp = function(done) {
del(paths.src.tmp, { force: _config.forceClean || false }, done);
};
} | javascript | {
"resource": ""
} | |
q41021 | train | function(addExtraWatchers) {
/* Watchers -------------------------------------------------------------- */
gulp.task('watch', ['serve'], function () {
gulp.watch(paths.src.es6, ['bundle-js:dev:clean']);
gulp.watch(paths.src.js, ['bundle-js:dev:clean']);
gulp.watch(paths.src.styles, ['styles']);
gulp.watch(paths.src.views, ['tpl-reload']);
gulp.watch(paths.out.base + '**/*', ['reload']);
addExtraWatchers && addExtraWatchers(gulp);
});
} | javascript | {
"resource": ""
} | |
q41022 | train | function(extensions) {
var
extensions = extensions || {},
devExts = extensions.development || [],
testExts = extensions.test || [],
prodExts = extensions.production || [];
gulp.task('default', ['development']);
gulp.task('post-install-development', [
'karma:dev',
'styles',
'bundle-js:dev:clean',
'tpl-precompile',
'watch'
].concat(devExts));
gulp.task('development', ['install-dev-dep'], function() {
gulp.start('post-install-development');
});
gulp.task('post-install-test', [
'lint',
'karma'
].concat(testExts), cleanTmp);
gulp.task('test', ['install-dev-dep'], function() {
gulp.start('post-install-test');
});
gulp.task('post-install-production', [
'styles',
'bundle-js:clean',
'tpl-precompile'
].concat(prodExts));
gulp.task('production', ['install-dep'], function() {
gulp.start('post-install-production');
});
} | javascript | {
"resource": ""
} | |
q41023 | train | function(name, resourcesNo, waitForMoreDemandingConsumers, debug){
/**
@memberof! qpp.SemaphoreMultiReservation#
@var {string} name - name of the semaphore
*/
this.name = name || "semaphore";
resourcesNo = resourcesNo || 1;
/**
@memberof! qpp.SemaphoreMultiReservation#
@private
@var {string} initialResources - initial (total) number of resources that semaphore has
*/
this.initialResources = resourcesNo;
/**
@memberof! qpp.SemaphoreMultiReservation#
@var {string} resourcesNo - currently available number of resources
*/
this.resourcesNo = resourcesNo;
/**
@memberof! qpp.SemaphoreMultiReservation#
@private
@var {string} waitingQueue - queue holding the list of waiting consumers (functions) for available resources
*/
this.waitingQueue = [];
/**
@memberof! qpp.SemaphoreMultiReservation#
@var {boolean} waitForMoreDemandingConsumers=true - defines if consumer can allocate resources even if other consumer waits for available resources (but needs more resources than currently available)
@example
var s = new Semaphore('s', 3);
var wP1 = s.wait(1); // fine, 2 resources left available
var wP2 = s.wait(3); // not fine (consumer 1 has to release)
// wP3 will be fine and resolved if {@link this.waitForMoreDemandingConsumers} === false
// or not fine and not resolved until consumer 1's resources are released (signaled)
// if {@link this.waitForMoreDemandingConsumers} === true (default)
var wP3 = s.wait(2);
*/
this.waitForMoreDemandingConsumers = typeof waitForMoreDemandingConsumers !== 'undefined' ? waitForMoreDemandingConsumers : true;
/**
@memberof! qpp.SemaphoreMultiReservation#
@var {boolean} debug - defines if debugging messages should be shown during Semaphore operations
*/
this.debug = typeof debug !== 'undefined' ? debug : false;
} | javascript | {
"resource": ""
} | |
q41024 | train | function(resourcesNo, debug){
resourcesNo = resourcesNo || 1;
/**
@memberof! qpp.SemaphoresHash#
@var {Array.<string,QPP.Semaphore>} semaphores - array hash of semaphores
*/
this.semaphores = {};
/**
@memberof! qpp.SemaphoresHash#
@private
@var {string} initialResources - initial (total) number of resources that SemaphoresHash has
*/
this.initialResources = resourcesNo;
/**
@memberof! qpp.SemaphoresHash#
@var {boolean} debug - defines if debugging messages should be shown during SemaphoresHash operations
*/
this.debug = typeof debug !== 'undefined' ? debug : false;
} | javascript | {
"resource": ""
} | |
q41025 | buildConfig | train | function buildConfig(
config, items, item, inheritableConfigs = {}, visitedItems = []
) {
let { id } = item
if (visitedItems.includes(id)) {
throw new Error(`Item "${id}" has cyclic dependencies`)
}
let _extends = item.extends || DEFAULT
let inheritedConfig = inheritableConfigs[_extends]
visitedItems.push(id)
if (!inheritedConfig) {
let parent = findOneById(items, _extends)
if (!parent) {
throw new Error(`Item "${id}" tries to extend a non-existent item`)
}
parent = buildConfig(
config, items, parent, inheritableConfigs, visitedItems
)
inheritedConfig = extractInheritableConfig(config, parent)
inheritableConfigs[parent.id] = inheritedConfig
}
return mergeConfigs(inheritedConfig, item)
} | javascript | {
"resource": ""
} |
q41026 | setCliConfiguration | train | function setCliConfiguration() {
return yargs
.usage('usage: $0 [options] <aws-elasticsearch-cluster-endpoint>')
.option('h', {
alias: 'host',
default: HOST || '127.0.0.1',
demand: false,
describe: 'Host IP Address',
type: 'string',
})
.option('p', {
alias: 'port',
default: PORT || 9200,
demand: false,
describe: 'Host Port',
type: 'number',
})
.option('r', {
alias: 'region',
default: REGION || 'us-west-2',
demand: false,
describe: 'AWS region',
type: 'string',
})
.option('e', {
alias: 'endpoint',
default: ENDPOINT,
demand: true,
describe: 'AWS Elasticsearch Endpoint',
type: 'string',
})
.option('c', {
alias: 'profile',
default: AWS_PROFILE || 'default',
demand: false,
describe: 'AWS Credentials Profile',
type: 'string',
})
.option('d', {
alias: 'debug',
default: DEBUG || false,
demand: false,
describe: 'Provides debug logging',
type: 'boolean',
})
.help()
.version()
.strict()
} | javascript | {
"resource": ""
} |
q41027 | CreateRows | train | function CreateRows(obj)
{
//Start the output
var out = '';
//Get all
for(var key in obj)
{
//Check the out
if(out !== '')
{
//Add a comma
out = out + ', ';
}
//Add the row
out = out + key + ' ' + obj[key];
}
//Return the output
return out;
} | javascript | {
"resource": ""
} |
q41028 | train | function () {
if (this.settings.parentElement === false)
return this.createErrorMessage("No parent element set!");
// This is the container in
// which the bar resides
this.progressBar = $("<progress>").attr({
"id": "progress-bar",
"value": 0,
"max": 100
}).appendTo(this.settings.parentElement);
this.progressLabel = $("<div>").attr({
"class": "progress-bar-label"
}).html("0%").appendTo(this.settings.parentElement);
var div = $("<div>").html(this.settings.name).appendTo(this.settings.parentElement);
} | javascript | {
"resource": ""
} | |
q41029 | train | function (progress) {
var _this = this;
this.progressBar.animate({
value: progress
}, 1, function() {
_this.onProgress(progress);
});
this.progress = progress;
} | javascript | {
"resource": ""
} | |
q41030 | onExec | train | function onExec (err, stdout, stderr) {
callback(null, {
err: err,
stdout: stdout,
stderr: stderr
});
} | javascript | {
"resource": ""
} |
q41031 | pnbinom | train | function pnbinom(size, prob, lowerTail, logp) {
logp = logp === true;
lowerTail = lowerTail !== false;
return function(x) {
if (utils.hasNaN(x, size, prob) ||
size < 0 || prob <= 0 || prob > 1 ||
utils.isInfinite(size)) {
return NaN;
}
if (size === 0) {
return utils.adjustLower(x >= 0 ? 1 : 0, lowerTail, logp);
}
if (x < 0) { return utils.adjustLower(0, lowerTail, logp); }
x = Math.floor(x + 1e-14);
return beta.pbeta(size, x + 1, lowerTail, logp)(prob);
};
} | javascript | {
"resource": ""
} |
q41032 | rnbinom | train | function rnbinom(size, prob) {
var rg;
if (size <= 0 || prob <= 0 || prob > 1) {
return function() { return NaN; };
}
if (prob === 1) { return function() { return 0; }; }
rg = rgamma(size, (1 - prob) / prob);
return function() { return rpois(rg())(); };
} | javascript | {
"resource": ""
} |
q41033 | train | function(size, prob) {
return {
d: function(x, logp) { return dnbinom(size, prob, logp)(x); },
p: function(q, lowerTail, logp) {
return pnbinom(size, prob, lowerTail, logp)(q);
},
q: function(p, lowerTail, logp) {
return qnbinom(size, prob, lowerTail, logp)(p);
},
r: function() { return rnbinom(size, prob)(); }
};
} | javascript | {
"resource": ""
} | |
q41034 | emit | train | function emit(name, next) {
var transport = that.transports[name];
if ((transport.level && that.levels[transport.level] <= that.levels[level])
|| (!transport.level && that.levels[that.level] <= that.levels[level])) {
transport.log(rec, function (err) {
if (err) {
err.transport = transport;
cb(err);
return next();
}
that.emit('logging', transport, rec);
next();
});
} else {
next();
}
} | javascript | {
"resource": ""
} |
q41035 | cb | train | function cb(err) {
if (callback) {
if (err) return callback(err);
callback(null, rec);
}
callback = null;
if (!err) {
that.emit('logged', rec);
}
} | javascript | {
"resource": ""
} |
q41036 | queryTransport | train | function queryTransport(transport, next) {
if (options.query) {
options.query = transport.formatQuery(query);
}
transport.query(options, function (err, results) {
if (err) {
return next(err);
}
next(null, transport.formatResults(results, options.format));
});
} | javascript | {
"resource": ""
} |
q41037 | addResults | train | function addResults(transport, next) {
queryTransport(transport, function (err, result) {
//
// queryTransport could potentially invoke the callback
// multiple times since Transport code can be unpredictable.
//
if (next) {
result = err || result;
if (result) {
results[transport.name] = result;
}
next();
}
next = null;
});
} | javascript | {
"resource": ""
} |
q41038 | first | train | function first(FIRST, rule) {
var terminals = new Set();
var read = true;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = rule[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var x = _step.value;
if (!read) break;
read = false;
if (x.type === 'leaf') {
terminals.add(x.terminal);
break;
}
(0, _util.setaddall)(terminals, (0, _jsItertools.filter)(function (y) {
return y !== _grammar.EW;
}, FIRST.get(x.nonterminal)));
read |= (0, _jsItertools.any)((0, _jsItertools.map)(function (y) {
return y === _grammar.EW;
}, FIRST.get(x.nonterminal)));
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
if (read) terminals.add(_grammar.EW);
return terminals;
} | javascript | {
"resource": ""
} |
q41039 | train | function() {
this._nextCalled = true;
if(this._collection.size() > 0) {
if(this._hasNextCalled) {
this._hasNextCalled = false;
this._pos --;
}
this._pos ++;
this._nextElement = this._collection.getAll()[this._pos];
if(this._nextElement !== undefined) {
return this._nextElement;
} else {
throw new Error("No such element.");
}
}
} | javascript | {
"resource": ""
} | |
q41040 | train | function() {
if(this._collection.getAll()[this._pos + 1]) {
this._hasNext = true;
} else {
this._hasNext = false;
}
if(!this._nextCalled) {
this._pos ++;
this._hasNextCalled = true;
}
return this._hasNext;
} | javascript | {
"resource": ""
} | |
q41041 | mkInsert | train | function mkInsert(table, obj) {
const ks = Object.keys(obj).map(x => `\`${x}\``);
const vs = Object.values(obj).map(toMysqlObj);
return `INSERT INTO \`${table}\`(${ks}) VALUES(${vs})`;
} | javascript | {
"resource": ""
} |
q41042 | toMysqlObj | train | function toMysqlObj(obj) {
if (obj === undefined || obj === null)
return "NULL";
switch (obj.constructor) {
case Date:
return `'${formatDate(obj)}'`;
case String:
return `'${obj.replace(/'/g, "''")}'`;
case Number:
return obj;
default:
throw new TypeError(`${util.inspect(obj)}`);
}
} | javascript | {
"resource": ""
} |
q41043 | train | function (chain) {
if (chain.readable) {
chain.chainAfter = chain.chainAfter || Pipe.Chain.prototype.chainAfter;
chain.nextChain = chain.nextChain || Pipe.Chain.prototype.nextChain;
}
if (chain.writable) { // Duplex
chain.chainBefore = chain.chainBefore || Pipe.Chain.prototype.chainBefore;
chain.previousChain = chain.previousChain || Pipe.Chain.prototype.previousChain;
}
chain.autoEnhance = true;
chain.enhanceForeignStream = chain.enhanceForeignStream || Pipe.Chain.prototype.enhanceForeignStream;
} | javascript | {
"resource": ""
} | |
q41044 | train | function (chain) {
if (chain.previousChain) {
chain.previousChain.unpipe(chain);
chain.previousChain.pipe(this);
chain.previousChain.nextChain = this;
}
if (this.autoEnhance) {
this.enhanceForeignStream(chain);
}
this.pipe(chain);
chain.previousChain = this;
this.nextChain = chain;
return this;
} | javascript | {
"resource": ""
} | |
q41045 | train | function(callback) {
ftpout.raw.pwd(function(err) {
if (err && err.code === 530) {
grunt.fatal('bad username or password');
}
callback(err);
});
} | javascript | {
"resource": ""
} | |
q41046 | train | function(callback) {
grunt.log.write(wrap('===== saving hashes... '));
ftpout.put(new Buffer(JSON.stringify(localHashes)), 'push-hashes', function(err) {
if (err) { done(err); }
grunt.log.writeln(wrapRight('[SUCCESS]').green);
callback();
});
} | javascript | {
"resource": ""
} | |
q41047 | train | function(localHashes, files, done) {
fetchRemoteHashes(function(err, remoteHashes) {
done(err, localHashes, remoteHashes, files);
});
} | javascript | {
"resource": ""
} | |
q41048 | rayVsLineSegment | train | function rayVsLineSegment(ray, segment) {
var result = lineIntersect.checkIntersection(
ray.start.x, ray.start.y, ray.end.x, ray.end.y,
segment.start.x, segment.start.y, segment.end.x, segment.end.y
);
// definitely no intersection
if (result.type == 'none' || result.type == 'parallel') return null;
// single intersection point
if (result.type == 'intersecting') return result.point;
// colinear, so now check if ray/segment overlap
if (segmentContainsPoint(segment, ray.start)) {
return ray.start;
} else {
// return segment endpoint that is
// - within ray
// - closest to ray start
var rayStart = new Vec2(ray.start);
var endpointsInRay = segmentEndpointsInRay(ray, segment);
return rayStart.nearest(endpointsInRay);
}
} | javascript | {
"resource": ""
} |
q41049 | train | function(elem){
if(!this.root){
this.root = struct.Node(elem);
this.tail = this.root;
this.size = 1;
return this;
// this.root.isRoot = true;
}
this.root.prepend(elem);
this.root = this.root.previous;
this.size += 1;
// this.add(elem,this.root);
return this;
} | javascript | {
"resource": ""
} | |
q41050 | train | function(elem){
if(!this.root){
this.root = struct.Node(elem);
this.tail = this.root;
this.size = 1;
return this;
// this.root.isRoot = true;
}
// this.add(elem);
this.tail.append(elem);
this.tail = this.tail.next;
this.size += 1;
return this;
} | javascript | {
"resource": ""
} | |
q41051 | train | function(){
if(!this.size) return;
var n = this.root, pr = n.previous, nx = n.next;
if(this.size === 1){
this.root = this.tail = null; this.size = 0;
return n;
}
nx.previous = pr;
delete this.root;
this.root = nx;
this.size -= 1;
return n;
} | javascript | {
"resource": ""
} | |
q41052 | markLinkElement | train | function markLinkElement(element, active_nr) {
var mark_wrapper;
// Always remove the current classes
element.classList.remove('active-link');
element.classList.remove('active-sublink');
if (element.parentElement && element.parentElement.classList.contains('js-he-link-wrapper')) {
markLinkElement(element.parentElement, active_nr);
}
if (!active_nr) {
return;
}
if (active_nr == 1) {
element.classList.add('active-link');
} else if (active_nr == 2) {
element.classList.add('active-sublink');
}
} | javascript | {
"resource": ""
} |
q41053 | Target | train | function Target(options = {}) {
options = clone(options);
let client = new Hipchatter(options.token);
let room = options.room;
delete options.token;
delete options.room;
let proto = {
message_format: 'html',
notify: false
};
for (let key in options) {
if (!options.hasOwnProperty(key)) {
break;
}
proto[key] = options[key];
}
return function(options, severity, date, message) {
let payload = clone(proto);
if (typeof payload.color !== 'string') {
switch(severity) {
case 'info':
payload.color = 'green';
break;
case 'warn':
payload.color = 'yellow';
break;
case 'error':
payload.color = 'red';
break;
default:
payload.color = 'gray';
break;
}
}
if (proto.message_format === 'html') {
payload.message = escape(message)
.replace(/\n/g, '<br/>')
.replace(/\t/g, ' ');
}
else {
payload.message = message;
}
client.notify(room, payload, function(err) {
if (err) {
console.log(err);
}
});
};
} | javascript | {
"resource": ""
} |
q41054 | dispatch | train | function dispatch() {
var commands = [].slice.call(arguments);
return function fn() {
var args = [].slice.call(arguments);
var result;
for (var i = 0; i < commands.length; i++) {
result = commands[i].apply(undefined, args);
if (result !== undefined) {
break;
}
}
return result;
};
} | javascript | {
"resource": ""
} |
q41055 | toArray | train | function toArray(obj) {
var key, val, arr = [];
for (key in obj) {
val = obj[key];
if (Array.isArray(val))
for (var i = 0; i < val.length; i++)
arr.push([ key, val[i] ]);
else
arr.push([ key, val ]);
}
return arr;
} | javascript | {
"resource": ""
} |
q41056 | assignDeep | train | function assignDeep(dest, source) {
if (source && source.constructor === Object) {
var sourceBaseKeys = Object.keys(source);
for (var i = 0; i < sourceBaseKeys.length; ++i) {
var sourceBaseKey = sourceBaseKeys[i];
var destinationField = dest[sourceBaseKey];
var sourceField = source[sourceBaseKey];
if (destinationField === undefined) {
dest[sourceBaseKey] = sourceField;
} else {
// Recursive assign.
assignDeep(destinationField, sourceField);
}
}
}
} | javascript | {
"resource": ""
} |
q41057 | check | train | function check(args, names) {
var msg = '',
name = '',
template = '{{ name }} coud not be empty!',
indexOf = Array.prototype.indexOf,
lenNames = names.length,
lenArgs = args.length,
lessArgs = lenArgs < lenNames,
emptyIndex = indexOf.call(args),
isEmpty = ~emptyIndex;
if (lessArgs || isEmpty) {
if (lessArgs)
name = names[lenNames - 1];
else
name = names[emptyIndex];
msg = Util.render(template, {
name: name
});
throw(Error(msg));
}
return check;
} | javascript | {
"resource": ""
} |
q41058 | type | train | function type(variable) {
var regExp = /\s([a-zA-Z]+)/,
str = {}.toString.call(variable),
typeBig = str.match(regExp)[1],
result = typeBig.toLowerCase();
return result;
} | javascript | {
"resource": ""
} |
q41059 | train | function(callback) {
var ret,
isFunc = Util.type.function(callback),
args = [].slice.call(arguments, 1);
if (isFunc)
ret = callback.apply(null, args);
return ret;
} | javascript | {
"resource": ""
} | |
q41060 | Sentinel | train | function Sentinel(label, propertiesObject) {
if (!(this instanceof Sentinel)) {
return new Sentinel(label, propertiesObject);
}
if (typeof label === 'object' && label) {
propertiesObject = label;
label = undefined;
}
if (typeof label === 'number') {
label = String(label);
} else if (typeof label !== 'undefined') {
if (typeof label !== 'string' || !label) {
throw new TypeError('Expected label to be a non-empty string or number.');
}
}
Object.defineProperties(this, {
_sentinel_id: {
value: ++instanceCount,
//enumerable to work with Chai's `deep-eql`.
enumerable: true
},
_sentinel_label: {
value: label
}
});
if (propertiesObject) {
Object.defineProperties(this, propertiesObject);
}
} | javascript | {
"resource": ""
} |
q41061 | _buildPaths | train | function _buildPaths() {
var home = os.homedir();
var path1 = path.resolve(home + '/Music/iTunes/iTunes Music Library.xml');
var path2 = path.resolve(home + '/Music/iTunes/iTunes Library.xml');
return [path1, path1];
} | javascript | {
"resource": ""
} |
q41062 | train | function() {
var parser, source;
source = this.source();
if (source == null) {
return;
}
parser = this.parser();
if (parser != null) {
return parser(source);
} else {
return source;
}
} | javascript | {
"resource": ""
} | |
q41063 | train | function (opts) {
// get the browser configuration & the browser module
var browserConf = {name: null};
var browser = opts.browserMo;
// prepare properties
this._initializeProperties(opts);
// create a new webdriver client instance
this.webdriverClient = new WD(browser, this.events);
// listen on browser events
this._startBrowserEventListeners(browser);
// assign the current browser name
browserConf.name = this.browserName;
// store desired capabilities of this session
this.desiredCapabilities = browser.getDesiredCapabilities(this.browserName, this.config);
this.browserDefaults = browser.driverDefaults;
this.browserDefaults.status = browser.getStatusDefaults(this.desiredCapabilities);
this.browserData = browser;
// set auth data
var driverConfig = this.config.get('driver.sauce');
browser.setAuth(driverConfig.user, driverConfig.key);
// launch the browser & when the browser launch
// promise is fullfilled, issue the driver:ready event
// for the particular browser
browser
.launch(browserConf, this.reporterEvents, this.config)
.then(this.events.emit.bind(this.events, 'driver:ready:sauce:' + this.browserName, browser));
} | javascript | {
"resource": ""
} | |
q41064 | train | function (opts) {
// prepare properties
this.actionQueue = [];
this.config = opts.config;
this.lastCalledUrl = null;
this.driverStatus = {};
this.sessionStatus = {};
// store injcted options in object properties
this.events = opts.events;
this.reporterEvents = opts.reporter;
this.browserName = opts.browser;
return this;
} | javascript | {
"resource": ""
} | |
q41065 | train | function (browser) {
// issue the kill command to the browser, when all tests are completed
this.events.on('tests:complete:sauce:' + this.browserName, browser.kill.bind(browser));
// clear the webdriver session, when all tests are completed
this.events.on('tests:complete:sauce:' + this.browserName, this.webdriverClient.closeSession.bind(this.webdriverClient));
return this;
} | javascript | {
"resource": ""
} | |
q41066 | train | function () {
var deferred = Q.defer();
// store desired capabilities of this session
this.desiredCapabilities = this.browserData.getDesiredCapabilities(this.browserName, this.config);
this.browserDefaults = this.browserData.driverDefaults;
this.browserDefaults.status = this.browserData.getStatusDefaults(this.desiredCapabilities);
// start a browser session
this._startBrowserSession(deferred, this.desiredCapabilities, this.browserDefaults);
return deferred.promise;
} | javascript | {
"resource": ""
} | |
q41067 | train | function () {
var result = Q.resolve();
// loop through all promises created by the remote methods
// this is synchronous, so it waits if a method is finished before
// the next one will be executed
this.actionQueue.forEach(function (f) {
result = result.then(f);
});
// flush the queue & fire an event
// when the queue finished its executions
result.then(this.flushQueue.bind(this));
return this;
} | javascript | {
"resource": ""
} | |
q41068 | train | function (sessionInfo) {
var defer = Q.defer();
this.sessionStatus = JSON.parse(sessionInfo).value;
this.events.emit('driver:sessionStatus:sauce:' + this.browserName, this.sessionStatus);
defer.resolve();
return defer.promise;
} | javascript | {
"resource": ""
} | |
q41069 | train | function (statusInfo) {
var defer = Q.defer();
this.driverStatus = JSON.parse(statusInfo).value;
this.events.emit('driver:status:sauce:' + this.browserName, this.driverStatus);
defer.resolve();
return defer.promise;
} | javascript | {
"resource": ""
} | |
q41070 | onError | train | function onError() { // {{{2
O.log.unhandled('LIRC ERROR', arguments);
delete this.socket;
setTimeout(connect.bind(null, this), 1000);
} | javascript | {
"resource": ""
} |
q41071 | extractParameters | train | function extractParameters(header) {
var SEPARATOR = /(?: |,)/g;
var OPERATOR = /=/;
return header.split(SEPARATOR).reduce(function (parameters, property) {
var parts = property.split(OPERATOR).map(function (part) {
return part.trim();
});
if (parts.length === 2)
parameters[parts[0]] = parts[1];
return parameters;
}, {});
} | javascript | {
"resource": ""
} |
q41072 | each | train | function each(object, callback) {
if (!object) { return true; }
if (object.forEach) { return object.forEach(callback); }
if (object instanceof Array) {
var length = array ? array.length : 0;
for(var index = 0; index < length; index++) {
callback(array[index], index);
}
}else{
for(var key in object) {
if (!object.hasOwnProperty(key)) { continue; }
callback(object[key], key);
}
}
return false;
} | javascript | {
"resource": ""
} |
q41073 | every | train | function every(object, callback) {
if (!object) { return true; }
if (object.every) { return object.every(callback); }
if (object instanceof Array) {
var length = array ? array.length : 0;
for(var index = 0; index < length; index++) {
if (!callback(array[index], index)) { return false; }
}
}else{
for(var key in object) {
if (!object.hasOwnProperty(key)) { continue; }
if (!callback(object[key], key)) { return false; }
}
}
return true;
} | javascript | {
"resource": ""
} |
q41074 | clone | train | function clone(object, deep) {
if (!object) { return object; }
var clone = object.prototype
? Object.create(object.prototype.constructor) : {};
for(var key in object) {
if (!object.hasOwnProperty(key)) { continue; }
clone[key] = deep ? clone(object[key], deep) : object[key];
}
return clone;
} | javascript | {
"resource": ""
} |
q41075 | train | function(paths) {
var base = Script.current(this).absolute;
each(paths, function(item, index) {
var path = paths[index] = URL.absolute(URL.clean(item), base);
if (path[path.length - 1] !== '/') {
paths[index] += '/';
}
});
return paths;
} | javascript | {
"resource": ""
} | |
q41076 | train | function(script) {
if (script.loader !== this) { return script.loader.load(script); }
Loader.loaded = false;
if (this.loaded[script.id]) { return true; }
if (this.failed[script.id]) {
throw new Error('No such file: ' + script.url);
}
this.pending[script.id] = script;
return false;
} | javascript | {
"resource": ""
} | |
q41077 | train | function() {
if (Loader.loading) { return false; }
var count = 0;
if (some(this.pending, function(script) {
count++;
if (script.satisfied()) {
Loader.loading = script;
script.module.install();
script.load();
return true;
}
return false;
}) || count === 0) { return true; }
return false;
} | javascript | {
"resource": ""
} | |
q41078 | train | function() {
var pending = this.pending,
script;
for(var name in pending) {
if (!pending.hasOwnProperty(name)) { continue; }
var cycle = pending[name].cycle();
if (cycle) {
cycle[0].allow(cycle[1]);
this.load(cycle[0]);
return true;
}
}
} | javascript | {
"resource": ""
} | |
q41079 | train | function(script) {
script.module.uninstall();
if (script.stopped || (!script.callback && Loader.loading !== script)) {
script.loader.load(script);
Loader.next();
return;
}
this.loaded[script.id] = script;
delete this.pending[script.id];
Loader.loading = null;
Loader.next();
} | javascript | {
"resource": ""
} | |
q41080 | train | function(script) {
script.module.uninstall();
if (Loader.loading === script) {
Loader.loading = null;
}
script.destroy();
if (!script.next()) {
delete this.pending[script.id];
this.failed[script.id] = script;
}
Loader.next();
} | javascript | {
"resource": ""
} | |
q41081 | train | function(url) {
var loaded = this.loaded,
pending = this.pending,
failed = this.failed,
relative = this.relative(url);
return loaded[relative] || pending[relative] || [failed[relative]];
} | javascript | {
"resource": ""
} | |
q41082 | train | function(callback) {
var original = Loader.using;
Loader.using = this;
try{
callback();
}finally{
Loader.using = original;
}
} | javascript | {
"resource": ""
} | |
q41083 | train | function(url) {
var paths = this.paths;
for(var index = 0; index < paths.length; index++) {
var path = paths[index];
if (path === url.substring(0, path.length)) {
return url.substring(path.length);
}
}
return url;
} | javascript | {
"resource": ""
} | |
q41084 | train | function() {
if (!this.remain.length) { return false; }
var next = this.remain.shift();
this.absolute = URL.absolute(this.url, next);
return true;
} | javascript | {
"resource": ""
} | |
q41085 | train | function() {
delete this.stopped;
if (this.callback) {
try{
this.module.exports = this.callback();
}catch(e) {
if (e === STOP_EVENT) {
this.onfail();
}else{
return this.onfail();
}
}
return this.onload();
}else{
this.create();
this.bind();
document.head.appendChild(this.tag);
}
} | javascript | {
"resource": ""
} | |
q41086 | train | function() {
if (this.events) { return; }
var tag = this.tag,
script = this,
prefix = '',
method = 'addEventListener';
// The alternative is nuking Redmond from orbit, its the only way to
// be sure...
if (!tag.addEventListener) {
prefix = 'on';
method = 'attachEvent';
}
function loaded(event) {
script.onload();
}
function failed(event) {
script.onfail();
}
function state(event) {
switch(tag.readyState) {
case 'complete': return loaded(event);
case 'error': return failed(event);
}
}
if (prefix === '') {
tag[method](prefix + 'error', failed);
tag[method](prefix + 'load', loaded);
}else{
tag[method](prefix + 'readystatechange', state);
}
this.events = {
loaded: loaded,
failed: failed,
state: state
};
return this;
} | javascript | {
"resource": ""
} | |
q41087 | train | function() {
var depends = this.depends,
allowed = this.allowed;
return every(depends, function(depend) {
return depend.loader.loaded[depend.id]
|| depend.loader.failed[depend.id]
|| allowed[depend.id];
});
} | javascript | {
"resource": ""
} | |
q41088 | train | function(requesters, parent) {
if (this.satisfied()) { return null; }
requesters = requesters || {};
var id = this.id;
if (requesters[id] && !parent.allowed[id]) {
return [parent, this];
}
requesters[id] = this;
var depends = this.depends;
for(var name in depends) {
if (!depends.hasOwnProperty(name)) { continue; }
var depend = depends[name],
result = depend.cycle(requesters, this);
if (result) { return result; }
}
delete requesters[id];
return null;
} | javascript | {
"resource": ""
} | |
q41089 | train | function() {
this.loaded = false;
this.stopped = true;
var current = Script.current(this.loader);
// Unbind and remove the relevant tag, if any.
this.destroy();
// Welcome traveller! You've discovered the ugly truth! This is
// the 'magic' of the require script, allowing execution to be
// halted until dependencies have been satisfied. Basically it:
//
// * Sets up top level error handlers
// * throws an error
// * catches that error at the top level
// * reverts the handling functionality back to its original state
//
// It is definitely not pretty, but by doing so we can halt
// execution of a script at an arbitrary point, as long as the stack
// does not have any `try{ ... }catch{ ... }` blocks along the way.
var existing = window.onerror,
tag = this.tag;
function handler(event) {
if (event.target !== window) {
return true;
}
if (root.removeEventListener) {
root.removeEventListener('error', handler, true);
}else root.detachEvent('onerror', handler);
window.onerror = existing;
return Event.cancel(event);
}
window.onerror = handler;
if (root.addEventListener) {
root.addEventListener('error', handler, true);
}else root.attachEvent('onerror', handler);
throw STOP_EVENT;
} | javascript | {
"resource": ""
} | |
q41090 | train | function(url, base) {
if (!url || url.indexOf('://') !== -1) { return url; }
var anchor = document.createElement('a');
anchor.href = (base || location.href);
var protocol = anchor.protocol + '//',
host = anchor.host,
path = anchor.pathname,
parts = filter(path.split('/'), function(part) { return part !== ''; });
each(url.replace(/\?.*/, '').split('/'), function(part, index) {
switch(part) {
case '..':
if (!parts.length) {
throw new Error('Path outside of root: ' + url);
}
parts.length--;
break;
case '.': break;
default: parts.push(part); break
}
});
return protocol + host + '/' + parts.join('/');
} | javascript | {
"resource": ""
} | |
q41091 | train | function(url) {
var index = url ? url.lastIndexOf('/') : -1;
return index == -1 ? url : url.substring(0, index + 1);
} | javascript | {
"resource": ""
} | |
q41092 | extract | train | function extract(type) {
for(var index = 0; index < 3; index++) {
if (typeof args[index] === type) { return args[index]; }
}
} | javascript | {
"resource": ""
} |
q41093 | getBasicInfo | train | function getBasicInfo() {
const result = {};
for (const key in info) {
if (info.hasOwnProperty(key)) {
result[key] = info[key]();
}
}
return result;
} | javascript | {
"resource": ""
} |
q41094 | checkPlatformSupported | train | function checkPlatformSupported(version, platform) {
const url = `${base}/${version}`;
if (platform === 'darwin') {
platform = 'osx64';
}
return new Promise((resolve, reject) => {
https.get(url, (res) => {
let body = '';
res.on('error', reject);
res.on('data', (d) => body += d.toString());
res.on('end', () => {
if (res.statusCode !== 200) {
return reject(new Error(body));
}
let $ = cheerio.load(body);
let links = [];
$('a[href]').each((i, link) => links.push(link.attribs.href));
for (let link of links) {
if (link.includes(platform)) {
return resolve(true);
}
}
resolve(false);
});
}).on('error', reject);
});
} | javascript | {
"resource": ""
} |
q41095 | train | function () {
return function (scribe) {
var jumpLinkCommand = new scribe.api.Command('createLink');
jumpLinkCommand.nodeName = 'A';
jumpLinkCommand.execute = function () {
var selection = new scribe.api.Selection(),
that = this;
var fullString = selection.selection.baseNode.textContent
if($(selection.selection.baseNode.parentNode).hasClass('is-jump-link')){
// Remove the jump link
$(selection.selection.baseNode).unwrap()
}else{
// Create the jump link
var startOffset = selection.range.startOffset
var numOfChar = selection.range.endOffset - startOffset
var replace = fullString.substr(startOffset, numOfChar)
if (selection.selection.baseNode.parentNode.nodeName === 'A'){
var parent = selection.selection.baseNode.parentElement
parent.classList.add('is-jump-link')
parent.setAttribute('name', replace)
}else{
replace = "<a class='is-jump-link' name=" + replace + ">" + replace + '</a>'
var newHtml = splice(fullString, startOffset, numOfChar, replace)
$(selection.selection.baseNode).replaceWith(newHtml)
}
}
};
// Set this as the jump linking plugin
scribe.commands.jumpLink = jumpLinkCommand;
};
} | javascript | {
"resource": ""
} | |
q41096 | train | function (svg) {
return svg
.replace(/zIndex="[^"]+"/g, '')
.replace(/isShadow="[^"]+"/g, '')
.replace(/symbolName="[^"]+"/g, '')
.replace(/jQuery[0-9]+="[^"]+"/g, '')
.replace(/url\([^#]+#/g, 'url(#')
.replace(/<svg /, '<svg xmlns:xlink="http://www.w3.org/1999/xlink" ')
.replace(/ (NS[0-9]+\:)?href=/g, ' xlink:href=') // #3567
.replace(/\n/, ' ')
// Any HTML added to the container after the SVG (#894)
.replace(/<\/svg>.*?$/, '</svg>')
// Batik doesn't support rgba fills and strokes (#3095)
.replace(/(fill|stroke)="rgba\(([ 0-9]+,[ 0-9]+,[ 0-9]+),([ 0-9\.]+)\)"/g, '$1="rgb($2)" $1-opacity="$3"')
/* This fails in IE < 8
.replace(/([0-9]+)\.([0-9]+)/g, function(s1, s2, s3) { // round off to save weight
return s2 +'.'+ s3[0];
})*/
// Replace HTML entities, issue #347
.replace(/ /g, '\u00A0') // no-break space
.replace(/­/g, '\u00AD') // soft hyphen
// IE specific
.replace(/<IMG /g, '<image ')
.replace(/height=([^" ]+)/g, 'height="$1"')
.replace(/width=([^" ]+)/g, 'width="$1"')
.replace(/hc-svg-href="([^"]+)">/g, 'xlink:href="$1"/>')
.replace(/ id=([^" >]+)/g, 'id="$1"') // #4003
.replace(/class=([^" >]+)/g, 'class="$1"')
.replace(/ transform /g, ' ')
.replace(/:(path|rect)/g, '$1')
.replace(/style="([^"]+)"/g, function (s) {
return s.toLowerCase();
});
} | javascript | {
"resource": ""
} | |
q41097 | train | function (options, chartOptions) {
var svg = this.getSVGForExport(options, chartOptions);
// merge the options
options = merge(this.options.exporting, options);
// do the post
Highcharts.post(options.url, {
filename: options.filename || 'chart',
type: options.type,
width: options.width || 0, // IE8 fails to post undefined correctly, so use 0
scale: options.scale || 2,
svg: svg
}, options.formAttributes);
} | javascript | {
"resource": ""
} | |
q41098 | train | function () {
var chart = this,
container = chart.container,
origDisplay = [],
origParent = container.parentNode,
body = doc.body,
childNodes = body.childNodes;
if (chart.isPrinting) { // block the button while in printing mode
return;
}
chart.isPrinting = true;
fireEvent(chart, 'beforePrint');
// hide all body content
each(childNodes, function (node, i) {
if (node.nodeType === 1) {
origDisplay[i] = node.style.display;
node.style.display = NONE;
}
});
// pull out the chart
body.appendChild(container);
// print
win.focus(); // #1510
win.print();
// allow the browser to prepare before reverting
setTimeout(function () {
// put the chart back in
origParent.appendChild(container);
// restore all body content
each(childNodes, function (node, i) {
if (node.nodeType === 1) {
node.style.display = origDisplay[i];
}
});
chart.isPrinting = false;
fireEvent(chart, 'afterPrint');
}, 1000);
} | javascript | {
"resource": ""
} | |
q41099 | train | function (options) {
var chart = this,
renderer = chart.renderer,
btnOptions = merge(chart.options.navigation.buttonOptions, options),
onclick = btnOptions.onclick,
menuItems = btnOptions.menuItems,
symbol,
button,
symbolAttr = {
stroke: btnOptions.symbolStroke,
fill: btnOptions.symbolFill
},
symbolSize = btnOptions.symbolSize || 12;
if (!chart.btnCount) {
chart.btnCount = 0;
}
// Keeps references to the button elements
if (!chart.exportDivElements) {
chart.exportDivElements = [];
chart.exportSVGElements = [];
}
if (btnOptions.enabled === false) {
return;
}
var attr = btnOptions.theme,
states = attr.states,
hover = states && states.hover,
select = states && states.select,
callback;
delete attr.states;
if (onclick) {
callback = function () {
onclick.apply(chart, arguments);
};
} else if (menuItems) {
callback = function () {
chart.contextMenu(
button.menuClassName,
menuItems,
button.translateX,
button.translateY,
button.width,
button.height,
button
);
button.setState(2);
};
}
if (btnOptions.text && btnOptions.symbol) {
attr.paddingLeft = Highcharts.pick(attr.paddingLeft, 25);
} else if (!btnOptions.text) {
extend(attr, {
width: btnOptions.width,
height: btnOptions.height,
padding: 0
});
}
button = renderer.button(btnOptions.text, 0, 0, callback, attr, hover, select)
.attr({
title: chart.options.lang[btnOptions._titleKey],
'stroke-linecap': 'round'
});
button.menuClassName = options.menuClassName || PREFIX + 'menu-' + chart.btnCount++;
if (btnOptions.symbol) {
symbol = renderer.symbol(
btnOptions.symbol,
btnOptions.symbolX - (symbolSize / 2),
btnOptions.symbolY - (symbolSize / 2),
symbolSize,
symbolSize
)
.attr(extend(symbolAttr, {
'stroke-width': btnOptions.symbolStrokeWidth || 1,
zIndex: 1
})).add(button);
}
button.add()
.align(extend(btnOptions, {
width: button.width,
x: Highcharts.pick(btnOptions.x, buttonOffset) // #1654
}), true, 'spacingBox');
buttonOffset += (button.width + btnOptions.buttonSpacing) * (btnOptions.align === 'right' ? -1 : 1);
chart.exportSVGElements.push(button, symbol);
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.